SQL Server Output Clause into a scalar variable

后端 未结 3 644
北海茫月
北海茫月 2020-11-30 07:05

Is there any \"simple\" way to do this or I need to pass by a table variable with the \"OUTPUT ... INTO\" syntax?

DECLARE @someInt int

INSERT INTO MyTable2(         


        
相关标签:
3条回答
  • 2020-11-30 07:33

    Over a year later... if what you need is get the auto generated id of a table, you can just

    SELECT @ReportOptionId = SCOPE_IDENTITY()
    

    Otherwise, it seems like you are stuck with using a table.

    0 讨论(0)
  • 2020-11-30 07:34

    You need a table variable and it can be this simple.

    declare @ID table (ID int)
    
    insert into MyTable2(ID)
    output inserted.ID into @ID
    values (1)
    
    0 讨论(0)
  • 2020-11-30 07:44

    Way later but still worth mentioning is that you can also use variables to output values in the SET clause of an UPDATE or in the fields of a SELECT;

    DECLARE @val1 int;
    DECLARE @val2 int;
    UPDATE [dbo].[PortalCounters_TEST]
    SET @val1 = NextNum, @val2 = NextNum = NextNum + 1
    WHERE [Condition] = 'unique value'
    SELECT @val1, @val2
    

    In the example above @val1 has the before value and @val2 has the after value although I suspect any changes from a trigger would not be in val2 so you'd have to go with the output table in that case. For anything but the simplest case, I think the output table will be more readable in your code as well.

    One place this is very helpful is if you want to turn a column into a comma-separated list;

    DECLARE @list varchar(max) = '';
    DECLARE @comma varchar(2) = '';
    SELECT @list = @list + @comma + County, @comma = ', ' FROM County
    print @list
    
    0 讨论(0)
提交回复
热议问题