【问题标题】:SQL Server: How do I get the value for the row I inserted?SQL Server:如何获取我插入的行的值?
【发布时间】:2010-12-28 12:00:41
【问题描述】:

我的 SQL Server 表在其他列之间有这些列。

AutoID,IdentitySpecification 设置为 True,GuidKey,默认值为 (newid())

AutoID   GuidKey
1        f4rc-erdd
2        gedd-rrds

有没有办法从插入的行中获取 GuidKey?

我需要 Scope_Identity() 之类的东西,不同之处在于我不想获取 AutoID 的内容,而是获取 GuidKey 列。

【问题讨论】:

    标签: sql sql-server tsql scope-identity


    【解决方案1】:

    Sql Server 2005/2008

    INSERT INTO myTable (SomeColumn)
        OUTPUT INSERTED.GuidKEY
    VALUES ('SomeData')
    

    【讨论】:

    • 如果你有不止一列存储一个 guid 值怎么办?
    【解决方案2】:

    当然:

     SELECT GuidKEy FROM [Table] WHERE AutoID= scope_identity()
    

    【讨论】:

      【解决方案3】:

      您可以执行以下操作:

      DECLARE @TempTable TABLE (GuidKey UNIQUEIDENTIFIER)
      
      INSERT INTO YourTable(Columns) 
        OUTPUT INSERTED.GuidKey INTO @TempTable(GuidKey) 
        VALUES(YourVALUES)
      

      这会将插入的 GuidKey 插入到@TempTable。然后,您可以从该表中提取值。

      【讨论】:

        【解决方案4】:

        对于uniqueidentifier,我执行以下操作:

        DECLARE @ID uniqueidentifier
        SET @ID = newId()
        
        ...
        

        然后我在插入语句中使用@ID。最后我使用SELECT @IDRETURN @ID 返回值

        【讨论】:

          猜你喜欢
          • 2022-09-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-08-13
          • 2010-09-07
          相关资源
          最近更新 更多