这里我将值插入两列,但现在我想要两个声明的值,它们刚刚创建:
Declare @ClientCompanyId int, @PersonId int
INSERT INTO ClientCompany (CompanyName)
VALUES ('WebDunia')
SELECT @ClientCompanyId = SCOPE_IDENTITY()
INSERT INTO Person (ClientCompanyId, Company, AddressLine1, AddressLine2, City, State, Country, Zip, HomePhone, WorkPhone, CellPhone, Fax, EmailId, Website)
VALUES (@ClientCompanyId, 'Google', 'Chicago', 'USA', 'Norway', 'ALASKA', 'CANADA', '12345', 12345678912, 12345, 56454, 'Fax', 'Email', 'Website')
SELECT SCOPE_IDENTITY() AS PersonId
我希望一次PersonId
和ClientCompanyId
。
答案 0 :(得分:2)
使用另一个变量集,与@ClientCompanyId
Declare @ClientCompanyId int,
@PersonId int
INSERT INTO ClientCompany(CompanyName) VALUES ('Google')
SELECT @ClientCompanyId=SCOPE_IDENTITY()
Insert into Person (ClientCompanyId,Company,AddressLine1, AddressLine2,
City, State, Country, Zip, HomePhone, WorkPhone,
CellPhone, Fax, EmailId, Website)
Values(@ClientCompanyId,'Google','Chicago','USA','Norway',
'ALASKA','CANADA','12345',12345678912,12345,56454,'Fax',
'Email','Website')
SELECT @ClientCompanyId, @PersonId=SCOPE_IDENTITY() <<<<<<<<<<<<<<<<<**Here**
答案 1 :(得分:1)
为什么不在第二次插入后用@PersonID复制你对@ClientCompanyID
的处理?
即。行SELECT SCOPE_IDENTITY() as PersonId
应该显示SELECT @PersonID = SCOPE_IDENTITY()
然后两个变量都会设置值。
我不知道这个sql在哪个上下文中运行,但是如果你需要两个值,你可以选择它们 - 或者在存储过程的情况下将它们作为out参数。
答案 2 :(得分:0)
试试这个:
INSERT INTO ClientCompany (CompanyName)
OUTPUT Inserted.ID
VALUES ('Google'), ('Microsoft')
它会返回所有插入ID的列表,我假设你的id列是ID。