Avatar of tommym121
tommym121
Flag for Canada asked on

SQL - Must declare the scalar variable "@ReturnVal".

This is the calling code
Use Test;

DECLARE @str nvarchar(max)
Exec sp_GetColummValueByIdx 'TmpUpdateTable', 'IID', 1, @str OUTPUT
Print '@str => ' + @str

This is the stored procedure
USE [Test]
GO
/****** Object:  StoredProcedure [dbo].[sp_GetColummValueByIdx]    Script Date: 05/24/2012 16:01:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[sp_GetColummValueByIdx]
      -- Add the parameters for the stored procedure here
      @TableName varchar(max),      
      @ColumnName varchar(max),
      @idx int,
      @ReturnVal nvarchar(max) OUTPUT
AS
BEGIN
      -- SET NOCOUNT ON added to prevent extra result sets from
      -- interfering with SELECT statements.
      SET NOCOUNT ON;

    -- Insert statements for procedure here
      --DECLARE @fmtString varchar(max)
      DECLARE @SQLQuery nvarchar(max)
      Set @SQLQuery =
            N'Select @ReturnVal=' +dbo.FormatStringForColumn(@TableName, @ColumnName)+ ' FROM ' + @TableName + ' WHERE idx='+CAST(@idx as varchar(max))
      
      Print '@SQLQuery -' + @SQLQuery
      EXEC (@SQLQuery)
        Print '@ReturnVal =>' + @ReturnVal
END

I got  the following result,  it complains (Must declare the scalar variable "@ReturnVal".)
Can anyone tell me why?


@SQLQuery -Select @ReturnVal= Cast(ISNULL(LTRIM(RTRIM('N'''+Replace([IID],'''','''''')+'''')),'NULL') as nvarchar(max)) FROM TmpUpdateTable WHERE idx=1
 
Msg 137, Level 15, State 1, Line 1
Must declare the scalar variable "@ReturnVal".
Microsoft SQL ServerMicrosoft SQL Server 2008Microsoft SQL Server 2005

Avatar of undefined
Last Comment
tommym121

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
dwkor

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
tommym121

ASKER
Thanks.
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck