I have the code below sitting in a stored procedure (SQL Server 2008). The code has been placed in a string in order to allow one of the parameters to have more than one value. The problem I have is when I test the SQL in SQL Server Management Studio it says that my string is not a valid identifier, and points to the line which I have put double ** around.
I cannot see what I have done wrong, and would like to know whether I have either missed something or ask whether this sort of query can be executed a dynamically. If the latter is not possible, then how does one pass a number of parameters to a query of this sort?
Thanks
DECLARE @SQL AS VARCHAR(MAX)
SELECT @SQL = 'select Production_Site, [Target],[Action],[Fail]'
SELECT @SQL = @SQL + ' from'
SELECT @SQL = @SQL + ' ('
SELECT @SQL = @SQL + ' select Production_Site, value, Period, YEAR, week'
SELECT @SQL = @SQL + ' from t_Pqe_Grocery'
SELECT @SQL = @SQL + ' unpivot ('
SELECT @SQL = @SQL + ' value'
SELECT @SQL = @SQL + ' for col in (Grocery_Packaging_And_Coding, Grocery_Measurable,'
SELECT @SQL = @SQL + ' Grocery_Appearance, Grocery_Aroma,'
**SELECT @SQL = @SQL + ' Grocery_Flavour, Grocery_Texture)) unp'**
SELECT @SQL = @SQL + ' ) src '
SELECT @SQL = @SQL + ' pivot '
SELECT @SQL = @SQL + ' ('
SELECT @SQL = @SQL + ' count(value)'
SELECT @SQL = @SQL + ' for value in ([Target], [Action], [Fail])'
SELECT @SQL = @SQL + ' ) piv'
SELECT @SQL = @SQL + ' where Production_Site IN (' + @Site + ') AND YEAR = ' +
CONVERT(varchar(50), CONVERT(BIGINT, @Year)) + ' AND Period = ' +
CONVERT(varchar(50), CONVERT(BIGINT, @Period)) + ' and Week = ' +
CONVERT(varchar(50), CONVERT(BIGINT, @Week))
EXECUTE @SQL
Change
EXECUTE @SQLtoEXECUTE (@SQL). I believe it’s the syntax problem.Try pasting this into SSMS and running it, it runs without quotes issue: