开发者

SQL - Stored Proc to Update table from Table Variable

I have a stored procedure which inserts records into a table using values from my table variable. (The table variable is sent to SQL from ASP.NET) It works perfect and looks like this...

CREATE PROCEDURE sp_SaveResponses 
(
@TableVariable S开发者_StackOverflowaveResponsesTableType READONLY
)
AS
BEGIN
INSERT INTO tbl_Responses
(
assessmentid, questionid, answerid
)
SELECT assessmentid, questionid, answerid
FROM @TableVariable
END

The above inserts one record into tbl_Responses for every row in @TableVariable.

The Problem Instead of INSERT, I would like to perform an UPDATE, but I can't get the syntax right.

Thanks for any help...!

UPDATE With some helpful hints, I was able to resolve this below...


You could try this (I haven't tested it) -

CREATE PROCEDURE sp_SaveResponses 
(
@TableVariable SaveResponsesTableType READONLY
)
AS
BEGIN
UPDATE tbl_Responses set questionid = @TableVariable.questionid
FROM @TableVariable
WHERE @TableVariable.assessmentid = tbl_Response.assessmentid 
END


Depending on what the join is between the table variable and the table that needs to be updated:

CREATE PROCEDURE sp_SaveResponses 
(
@TableVariable SaveResponsesTableType READONLY
)
AS
BEGIN
    UPDATE 
        tbl_Responses 
    SET 
        questionid = @TableVariable.questionid
    FROM 
        @TableVariable T1
        JOIN tbl_Responses T2 ON T1.assessmentid = T2.assessmentID
END


Thanks to @ipr1010 and @cob666 whose answers led me in the right direction... Here is the solution.

UPDATE tbl_Responses SET answerid = T1.answerid
FROM @TableVariable T1
WHERE tbl_Responses.assessmentid = T1.assessmentid AND tbl_Responses.questionid = T1.questionid

Naming @TableVariable T1 resolved the "must declare scalar variable..." issue. I also needed to update my WHERE clause or all values were updated with the first value in @TableVariable.

I wish I could vote you guys up but apparently my street cred is too weak!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜