I am trying to create a stored procedure that outputs records to a table. Each day the sproc is run, I would like it to output it to a table name and concatenate the current date to the table name. This is what I wrote, but the error I'm getting is when it's building the SQL select statement. It's not recognizing the @TableName variable when it starts to build the SELECT statement. Any ideas? Thanks.
DECLARE @TableName varchar(50), @SQL varchar(500)
SET @TableName = (convert(varchar(100),'dbUT_open_ar_' + CONVERT(varchar(8),GETDATE(),112)))
SET @SQL = ('SELECT sap_ShipToCustomerID AS ShipToCustomer, sap_BillToCustomerID AS BillToCustomer, sap_InvoiceDate AS InvoiceDate, sap_Amount AS Amount,
sap_ReferenceFrom AS ReferenceFrom INTO ' + @TableName + ' FROM dbo.open_ar WHERE (status_ready_for_upload = ' + '''' + 'Y' + '''')
EXEC @SQL
DECLARE @TableName varchar(50), @SQL varchar(500)
SET @TableName = (convert(varchar(100),'dbUT_open_ar_' + CONVERT(varchar(8),GETDATE(),112)))
SET @SQL = ('SELECT sap_ShipToCustomerID AS ShipToCustomer, sap_BillToCustomerID AS BillToCustomer, sap_InvoiceDate AS InvoiceDate, sap_Amount AS Amount,
sap_ReferenceFrom AS ReferenceFrom INTO ' + @TableName + ' FROM dbo.open_ar WHERE (status_ready_for_upload = ' + '''' + 'Y' + '''')
EXEC @SQL