mssql多个查询插入查询和结果

时间:2013-07-25 13:15:52

标签: sql-server insert

在php中我一次执行多个查询,查询是在一个大变量中写的。 这些是插入查询,我必须检索在db中创建的记录的每个自动增量“id”。怎么做 ? 检索到的结果集似乎没有保留每个结果,只有一个结果。

1 个答案:

答案 0 :(得分:0)

我认为您正在讨论插入语句中的OUTPUT子句。

http://msdn.microsoft.com/en-us/library/ms177564.aspx

CREATE TABLE #t (id int identity (1, 1), f1 nvarchar(20 ) ) --the table that has the identities
CREATE TABLE #ids ( id int ) --the table to store the inserts into table #t

INSERT INTO #t ( f1 ) OUTPUT INSERTED.id INTO #ids SELECT N'AAAA'
INSERT INTO #t ( f1 ) OUTPUT INSERTED.id INTO #ids SELECT N'BBBB'
INSERT INTO #t ( f1 ) OUTPUT INSERTED.id INTO #ids SELECT N'CCCC'

SELECT * FROM #t

SELECT * FROM #ids

另一种方法是使用@@IDENTITYSCOPE_IDENTITY() SQL Authority link discussing/comparing them

CREATE TABLE #t (id int identity (1, 1), f1 nvarchar(20 ) )
CREATE TABLE #ids ( id int )

INSERT INTO #t ( f1 ) SELECT N'AAAA'
INSERT INTO #ids SELECT @@IDENTITY --OR you can use SELECT SCOPE_IDENTITY()

INSERT INTO #t ( f1 ) SELECT N'BBBB'
INSERT INTO #ids SELECT @@IDENTITY --OR you can use SELECT SCOPE_IDENTITY()

INSERT INTO #t ( f1 ) SELECT N'CCCC'
INSERT INTO #ids SELECT @@IDENTITY --OR you can use SELECT SCOPE_IDENTITY()

SELECT * FROM #t
SELECT * FROM #ids
相关问题