Question

I have a requirement in SQL Server 2008 R2 to pass in many rows for an update to many rows. I decided to try a Table Valued Parameter to accomplish this. First - I created the type on the server.

CREATE TYPE [dbo].[crm_question_idx_type] AS TABLE(
    [survey_question_id] [int] NOT NULL,
    [row_index] [int] NOT NULL,
     PRIMARY KEY (survey_question_id)
)
GO

This went fine but the problem arose when attempting to create the Stored Procedure to use the new type. The code for creating the new procedure is:

CREATE PROCEDURE dbo.crm_question_index_update
(
@question_idx dbo.crm_question_idx_type READONLY
)
AS

SET NOCOUNT ON

UPDATE crm_survey_question 
SET crm_survey_question.row_index = @question_idx.row_index
FROM crm_survey_question 
INNER JOIN @question_idx 
    ON crm_survey_question.survey_question_id =  @question_idx.survey_question_id

When I attempt to compile this on the server I get the following error:

Msg 137, Level 16, State 1, Procedure crm_question_index_update, Line 10
Must declare the scalar variable "@question_idx".

Now in my code @question_idx is an input parameter of type dbo.crm_question_idx so I can't understand why this error is popping up.

Was it helpful?

Solution

Aliases are your friend. In this case not only do they simplify the amount of code, but they are required when referencing table variables or TVPs.

UPDATE c
  SET c.row_index = q.row_index
  FROM dbo.crm_survey_question AS c
  INNER JOIN @question_idx AS q
  ON c.survey_question_id = q.survey_question_id;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top