我有一个由
生成的表Partners
CREATE TABLE Partners (
id UNIQUEIDENTIFIER NOT NULL DEFAULT NEWID(),
name NVARCHAR(50) NOT NULL,
email NVARCHAR(254) NOT NULL, -- 254 is optimal length according to http://stackoverflow.com/questions/1199190/what-is-the-optimal-length-for-an-email-address-in-a-database
PRIMARY KEY (id)
);
尝试插入行并检索插入行的id
:
CREATE PROCEDURE AddPartner
@name NVARCHAR(50), @email NVARCHAR(254)
AS
BEGIN
SET NOCOUNT ON
INSERT INTO Partners (name,email)
OUTPUT INSERTED.id INTO @new_guid
VALUES (@name,@email)
SELECT @new_guid
END
假设我想(1)调用AddPartner
(name,email)
等于('some dude','dude192@gmail.com
)并返回id
(称之为dude_id
)以便我可以稍后(2)当我插入另一行时使用它:
INSERT INTO Answers (question_id,partner_id,val) VALUES (1,dude_id,24);
我该怎么做?并且(1)和(2)之间的GO
语句会破坏一切吗?
答案 0 :(得分:0)
将Output Parameter
添加到您的程序
CREATE PROCEDURE Addpartner (@name NVARCHAR(50),
@email NVARCHAR(254),
@new_guid UNIQUEIDENTIFIER output)
AS
BEGIN
SET NOCOUNT ON
INSERT INTO Partners
(name,email)
OUTPUT INSERTED.id INTO @new_guid
VALUES (@name,@email)
END
DECLARE @new_guid AS UNIQUEIDENTIFIER
EXEC Addpartner 'some dude', 'dude192@gmail.com', @new_guid output
INSERT INTO Answers
(question_id,partner_id,val)
VALUES (@output_identity,'dude_id',24);