I’m trying my first dynamic sql stored procedure. I need to append the exact same records into multiple tables with the same column names. What I have compiles, but when it runs I get ‘invalid column name ‘TradeDate. The driver sproc is first below, then the sproc containing the dynamic statement. If anyone could help, that’d be great..
ALTER PROCEDURE dbo.StoredProcedure2
AS
DECLARE @tableName varchar(120)
SET @tableName = 'tblDailyATR'
EXEC sprocAddDatesAndSymbolsToAggregatedStudy @tableName
RETURN
ALTER PROCEDURE dbo.sprocAddDatesAndSymbolsToAggregatedStudy
@table varchar(120)
AS
DECLARE @tableName varchar(120)
SET @tableName = @table
EXEC(
'INSERT INTO ' + @tableName + '(Symbol, TradeDate)
SELECT Symbol, TradingDate
FROM (SELECT tblSymbolsMain.Symbol, tblTradingDays.TradingDate
FROM tblSymbolsMain CROSS JOIN tblTradingDays
WHERE (tblTradingDays.TradingDate <= dbo.NextAvailableDataDownloadDate())) AS T1
WHERE (NOT EXISTS (SELECT TradeDate, Symbol
FROM' + @tableName +
' WHERE (TradeDate = T1.TradingDate) AND (Symbol = T1.Symbol)))')
RETURN
You’re missing a space after the “FROM” in this line:
Should be
Otherwise it’s going to try running SELECT FROMTABLE.