You tried something like:
DECLARE @FiscalYear INT, @DataSource NVARCHAR(25), @SQL NVARCHAR(250); SET @DataSource = N'CustomerCosts20120328'; SET @SQL = N'SELECT DISTINCT @FiscalYear = FiscalYear FROM ' + @DataSource; EXEC sp_executesql @SQL, N'@FiscalYear INT OUTPUT', @FiscalYear OUTPUT; PRINT @FiscalYear;
You need to make sure that you prefix nvarchar strings with N, for example. SELECT @SQL = N'SELECT ...
Also, you know that if a query returns multiple rows, the value assigned by @FiscalYear is completely arbitrary, right? Although you can expect a single value from this table, it can't hurt to use MAX() or TOP 1 ... ORDER BY to ensure that only one predictable value is ever assigned.
Aaron bertrand
source share