Sac*_*eph 2 t-sql sql-server stored-procedures
我有存储过程,在一些表中插入/更新记录.这些表的某些列具有默认值或自动递增.这就是我所拥有的:
ALTER PROCEDURE [dbo].[Usp___NewExpense]
@iCampaignID int,
@iCategory int,
@iUserID int,
@dDate Date,
@iAmountInINR int,
@strComments VarChar(200)
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO dbo.Tbl_Expenses(iCampaignID, iCategory, dDate, iAmountInINR, strComments)
VALUES (@iCampaignID, @iCategory, @dDate, @iAmountInINR, @strComments);
-- How to get the record inserted using the above statement here without using triggers
-- or another select statement, so that I can assign values to the following variables?
Declare @justInsertedValue1 type1;
Declare @justInsertedValue2 type2;
Declare @justInsertedValue3 type3;
INSERT INTO dbo.Tbl_SomeOtherTable(col1, col2, col3)
VALUES (justInsertedValue1, justInsertedValue2, justInsertedValue3);
END
GO
Run Code Online (Sandbox Code Playgroud)
Tbl_Expenses有大约9列,其中两列有默认值,两列有自动增量设置.如何在我的INSERT陈述下方获得刚刚插入的记录?
我知道我可以使用SCOPE_IDENTITY()然后a SELECT,但查询可能会使它效率低下(我是对的吗?).
(通过获取刚刚插入的记录,我的意思是刚刚插入的记录的所有字段的值)
编辑:我没有为INSERT语句中的所有字段指定值.由于DEFAULT/AUTO INCREMENT约束,我希望SQL Server自动插入这些值.
您可以使用该OUTPUT子句.您甚至可以将两者inserts合并为一个复合:
create table T1 (ID int IDENTITY(1,1) not null,ColA varchar(10) not null)
create table T2 (ID int IDENTITY(1,1) not null,T1ID int not null,ColB varchar(10) not null)
--Look ma! no local variables at all
insert into T2 (T1ID,ColB)
select t1.ID,'def'
from (
insert into T1(ColA)
output inserted.ID
values ('abc')
) t1
select * from T1
select * from T2
Run Code Online (Sandbox Code Playgroud)
结果:
ID ColA
----------- ----------
1 abc
ID T1ID ColB
----------- ----------- ----------
1 1 def
Run Code Online (Sandbox Code Playgroud)