2016-02-03 52 views
0

我具有由如何檢索並存儲這些指導以備後用?

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生成的表Partners

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','[email protected])並返回id(稱爲dude_id),這樣我可以在以後插入另一行時使用它:

INSERT INTO Answers (question_id,partner_id,val) VALUES (1,dude_id,24); 

我到底該怎麼做? (1)和(2)之間會有GO聲明破壞一切嗎?

+1

如果你沒有在進口時的ID檢查。 http://stackoverflow.com/questions/42648/best-way-to-get-identity-of-inserted-row –

回答

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', '[email protected]', @new_guid output 

INSERT INTO Answers 
      (question_id,partner_id,val) 
VALUES  (@output_identity,'dude_id',24); 
+0

'id'是'UNIQUEIDENTIFIER',而不是'INT' – user5648283

+0

@ user5648283 - 現在檢查 –

+0

我在'OUTPUT INSERTED.ID INTO @ new_guid'行中得到錯誤'必須聲明表變量「@new_guid」.' – user5648283

相關問題