SET @SQLSTATEMENT = 'INSERT INTO #MAX_STORAGE
SELECT MAX(A.[ROW])
FROM
(SELECT *
FROM [DATABASE].[dbo].[Refined_Est_Probability_09_MODIFIED]
WHERE
[FIPST_ENT] = ' + @FIPST_ENT + '
AND [FIPCNTY_ENT] = ' + @FIPCNTY_ENT + '
AND [SIC_ENT] = ' + @SIC2_ENT + '
AND [FMSZ_ENT] = ' + @FMSZENT_ENT + '
AND [ESTABLISHMENTS_AVAILABLE_FMSZEST <= ' + @MAXIMUM_FMSZEST+'] > 0) A'
EXEC(@SQLSTATEMENT)
I was running the dynamic SQL query above as part of a stored procedure I had written and got the following error:
Msg 207, Level 16, State 1, Line 7
Invalid column name 'A'.
I then changed my query so that it looked like this (eliminated the alias A):
SET @SQLSTATEMENT =
'INSERT INTO #MAX_STORAGE
SELECT
MAX([ROW])
FROM
(SELECT *
FROM [DATABASE].[dbo].[Refined_Est_Probability_09_MODIFIED]
WHERE [FIPST_ENT] = ' + @FIPST_ENT + '
AND [FIPCNTY_ENT] = ' + @FIPCNTY_ENT + '
AND [SIC_ENT] = ' + @SIC2_ENT + '
AND [FMSZ_ENT] = ' + @FMSZENT_ENT + '
AND [ESTABLISHMENTS_AVAILABLE_FMSZEST <= ' + @MAXIMUM_FMSZEST + '] > 0)'
EXEC(@SQLSTATEMENT)
But I still ran into an error (this time different):
Msg 102, level 15, state 1, line 9
Incorrect syntax near ')'
I declared the following variables earlier in the procedure with their respective data types/lengths seen next to them:
- @FIPST_ENT CHAR(2)
- @FIPCNTY_ENT CHAR(3)
- @SIC2_ENT CHAR(2)
- @FMSZENT_ENT CHAR(1)
- @MAXIMUM_FMSZENT CHAR(1)
- @SQLSTATEMENT VARCHAR(MAX)
Before this dynamic SQL statement was reached in the stored procedure, the temporary table #MAX_STORAGE was already created and contains only one column of datatype int.
Am I missing something I'm doing wrong? Any help would be greatly appreciated.
Thanks.
AND [ESTABLISHMENTS_AVAILABLE_FMSZEST<='+@MAXIMUM_FMSZEST+'] > 0)'do you have column names with a<=in them?@MAXIMUM_FMSZESTvalues (ranging from 1-9, A-C). That's why I needed dynamic SQL because that column changes every iteration depending on what the@MAXIMUM_FMSZESTvalue is. Thus, if@MAXIMUM_FMSZEST= 9, the column I want to be greater than 0 would be[ESTABLISHMENTS_AVAILABLE_FMSZEST<=9]. But to answer your question, yes the<=part is in the column name.PRINT @SQLSTATEMENTto see what is wrong ;-)