如何获取我在 SQL 中输入的值

How to get the value I entered in SQL

提问人:Marcelo Bittar 提问时间:11/4/2023 最后编辑:marc_sMarcelo Bittar 更新时间:11/6/2023 访问量:92

问:

我正在使用以下查询将值存储在表中:

INSERT INTO [dbo].[TB_Templates] ([DescTemplate], [Template], [User])
VALUES ('teste', 'teste', 'teste')

存储值的表包含以下列:

[IDTemplate] [int] IDENTITY(1,1) NOT NULL
[DescTemplate] [varchar](255) NOT NULL
[Template] [varchar](max) NOT NULL
[User] [varchar](255) NOT NULL

存储此值后,我需要知道使用我插入的行创建的 ID,以便在 C# Web API 中使用该值。

我有什么办法知道哪个是创建的吗?IDTemplate

C# .NET SQL-Server dapper

评论

0赞 Fildor 11/4/2023
您的查询中缺少“)”。我想这只是一个错别字?
2赞 Ken White 11/4/2023
SCOPE_IDENTITY()是你要找的吗?(该链接中还讨论了@@IDENTITY。
0赞 Xedni 11/5/2023
查看 stackoverflow.com/questions/1920558/... 了解一些选项及其差异

答:

4赞 derloopkat 11/4/2023 #1

从服务方法中返回刚添加的行的整数。

return connection.QueryFirst<int>(
    @"INSERT INTO [dbo].[TB_Templates] ([DescTemplate] ,[Template] ,[User])
      VALUES (@descTemplate, @template, @user);

      SELECT SCOPE_IDENTITY();",
    new { descTemplate,  template, user }
);
-1赞 Gesuele Russello 11/6/2023 #2

几个建议,如果您可以将插入内容放入这样的存储过程中

CREATE PROCEDURE dbo.spClient_Upsert
    @ClientID INT OUTPUT,
    @ClientName NVARCHAR(100),
    @ClientCode NVARCHAR(12)
AS
BEGIN
    SET NOCOUNT ON;

    -- Check if the record already exists based on the unique constraint
    IF EXISTS (SELECT 1 FROM dbo.Client WHERE ClientCode = @ClientCode)
    BEGIN
        -- Update the existing record
        UPDATE dbo.Client
        SET
            ClientName = @ClientName
        WHERE ClientCode = @ClientCode;

        SET @ClientID = (SELECT ClientID FROM dbo.Client WHERE ClientCode = @ClientCode);
    END
    ELSE
    BEGIN
        -- Insert a new record
        INSERT INTO dbo.Client (ClientName, ClientCode)
        VALUES (@ClientName, @ClientCode);

        SET @ClientID = SCOPE_IDENTITY();
    END
END;


        DynamicParameters p = new();
        p.Add(name: "@ClientID", dbType: DbType.Int32, direction: ParameterDirection.Output);
        p.Add(name: "@ClientName", data.ClientName);
        p.Add(name: "@ClientCode", data.ClientCode);
        p.Add(name: "@output", dbType: DbType.Int32, direction: ParameterDirection.ReturnValue);

    using IDbConnection connection = new SqlConnection(connectionString);

    await connection.ExecuteAsync(storedProcedureName: "[dbo].[spClient_Upsert]", p, commandType: CommandType.StoredProcedure);
     
  int ClientID = p.Get<int>(name: "@ClientID");