I am trying to pass in a variable in the IN clause and in googling for solutions I did the following but getting errors. Any help and/or direction would be appreciated.
My code is listed first then the errors are found below.
My code:
DECLARE @OwnerSysID varchar(500)
SET @OwnerSysID = '3, 3476, 3511'
DECLARE @sql nvarchar(4000)
SET @sql = 'Select AllPosiable.UserID, AllPosiable.AgentSysID, 0' +
'From (' +
'Select AgentSysID, UserID' +
'From (' +
'Select AGT_Agent.AgentSysID' +
'From AGT_Agent' +
'Where OwnerSysID IN ('+@OwnerSysID+')' +
'AND AgentName NOT LIKE %Texas State Low Cost%' +
'AND AgentName NOT LIKE %TSLC%' +
') as AgentIDs ' +
'Full Join (' +
'Select DISTINCT IW_UserAgentRelationship.UserID' +
'From AGT_Agent' +
'Left Join IW_UserAgentRelationship' +
'On IW_UserAgentRelationship.AgentID = AGT_Agent.AgentSysID' +
'Where OwnerSysID IN ('+@OwnerSysID+')' +
'And IW_UserAgentRelationship.isDefault = 1' +
'AND AgentName NOT LIKE %Texas State Low Cost%' +
'AND AgentName NOT LIKE %TSLC%' +
') As UserIDs On 1=1' +
') as AllPosiable' +
'Left Join IW_UserAgentRelationship' +
'On IW_UserAgentRelationship.AgentID = AllPosiable.AgentSysID' +
'And IW_UserAgentRelationship.UserID = AllPosiable.UserID' +
'Where IW_UserAgentRelationship.AgentID Is NULL'
EXEC sp_executesql @sql;
Errors:
Msg 156, Level 15, State 1, Line 1
Incorrect syntax near the keyword 'Select'.
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near 'OwnerSysID'.
Msg 156, Level 15, State 1, Line 1
Incorrect syntax near the keyword 'Join'.
Thank you.
PRINT @sqlto see what the statement looks like??? If you haven't, do it. Then you'll probably find out what's wrong.@OwnerSysID? That would allow you to build predicates that use a variable number of arguments without having to resort to dynamic SQL.