I'm trying to write dynamic SQL for a SP to extract data from 2 joined tables. However I'm getting a couple of errors that I can't seem to resolve (maybe I'm just going boss-eyed). Or is it the case that joins cant be handle with dynamic SQL!Here's the SPALTER Proc [dbo].[SpTEST] ( @TableName AS VARCHAR(30) ,@RelField AS VARCHAR(30) ,@StartDate AS DATE ,@EndDate AS DATE )AS BEGIN DECLARE @TESTString NVARCHAR(MAX) SET @TESTString = CONCAT( 'SELECT ReferralID ,DateReceived ,DateClosed FROM ', @TableName, ' AS r WHERE ', @RelField, ' >= ', '''', @StartDate,'''', ' AND ', @RelField, ' <= ', '''', @EndDate,'''','Left join( SELECT CnReferralID ,CnTestID FROM TESTTABLE2 )cOn r.ReferralID = c. CnTestID') EXECUTE sp_executesql @TESTString END
Here's The ExecuteDECLARE @return_value intEXEC @return_value = [dbo].[SpTEST] @TableName = N'TestTable1', @RelField = N'DateClosed', @StartDate = '2000-01-01', @EndDate = '2017-01-01'SELECT 'Return Value' = @return_valueGO
And these are the error messagesMsg 156, Level 15, State 1, Line 9Incorrect syntax near the keyword 'Left'.Msg 102, Level 15, State 1, Line 18Incorrect syntax near 'c'.(1 row(s) affected)
This has been driving me nuts for about 3 hours now.