0

Why am I getting an error statement here with the following? incorrect syntax near 'in'?

INSERT INTO Staging.dbo.progress execute('SELECT ID
    FROM Staging.dbo.tempstudents WHERE StartTerm in' + @progressReportTerm);
GabrielVa
  • 2,353
  • 9
  • 37
  • 59

1 Answers1

1

Assuming that you are using SQL Server, execute does not take expressions. So you need to construct the query beforehand:

declare @sql nvarchar(max);

select @sql = '
SELECT ID
FROM Staging.dbo.tempstudents
WHERE StartTerm in ' + @progressReportTerm;

INSERT INTO ODS_Staging.dbo.progress
    exec(@sql);

You no doubt have a good reason for using dynamic SQL here. However, that is probably not really a requirement. And the dynamic SQL might be introducing a SQL injection risk. It is definitely introducing a potential for hard-to-debug syntax errors.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
  • 1
    Don't do this, it's not that it *might* be open to injection, it **will** be. Use a table table parameter. – Thom A May 21 '21 at 12:34