I was trying to have the @sqlstring to run 3 times based on the months available from other file and these results all to be union to #table.
- When I included the "memberid in ('00001', '00002','00003')", the error message is "Incorrect syntax near '00001'".
- When I excluded the memberid, the error message is "Msg 214, Level 16, State 3, Procedure sp_executesql, Line 1 [Batch Start Line 1268] Procedure expects parameter '@params' of type 'ntext/nchar/nvarchar'."
How can I fix the following query?
DECLARE @Month VARCHAR(2)
DECLARE @Month1 VARCHAR(2)
DECLARE @Month2 VARCHAR(2)
DECLARE @Month3 VARCHAR(2)
DECLARE @Year VARCHAR(4)
DECLARE @Year1 VARCHAR(4)
DECLARE @Year2 VARCHAR(4)
DECLARE @Year3 VARCHAR(4)
DECLARE @SQLSTRING NVARCHAR(MAX)
SET @MONTH1 = N'SELECT MONTH FROM #period WHERE ROW = 1'
SET @MONTH2 = N'SELECT MONTH FROM #period WHERE ROW = 2'
SET @MONTH3 = N'SELECT MONTH FROM #period WHERE ROW = 3'
SET @YEAR1 = N'SELECT YEAR FROM #period WHERE ROW = 1'
SET @YEAR2 = N'SELECT YEAR FROM #period WHERE ROW = 2'
SET @YEAR3 = N'SELECT YEAR FROM #period WHERE ROW = 3'
SET @SQLSTRING = N'select memberid, sales, @MONTH as month, @YEAR as svyear
from member@Month where month = @month and memberid in ('00001', '00002','00003')'
INSERT INTO #table
EXECUTE sp_executesql @SQLSTRING, @MONTH=@MONTH1, @YEAR=@YEAR1
INSERT INTO #table
EXECUTE sp_executesql @SQLSTRING, @MONTH=@MONTH2, @YEAR=@YEAR2
INSERT INTO #table
EXECUTE sp_executesql @SQLSTRING, @MONTH=@MONTH3, @YEAR=@YEAR3;
DECLAREthe variables as avarchar(2)(or(4)), but then try toSETtheir values as annvarcharthat is far larger than 2/4 characters? - Larnu@Monthand@Year. Perhaps sample data and expected results will help us understand better what your real goal is here. - Larnu