I am passing a list of employee IDs to my ado.net query. Sometimes my list is empty so I am getting error on this condition.
The error saying: Incorrect syntax near ')'.
Here is my code:
var emps = String.Join(",", empList.Keys);
StringBuilder sql = new StringBuilder(
$@"select [Id]
FROM [Test].[dbo].[Employees]
Where [Id] NOT IN {emps}"
);
2
Answers
Check your emp list beforehand and only add the WHERE clause to the StringBuilder if the list in not empty.
ALSO there is an extra ‘)’ in your sql string,
Where [Id] NOT IN {emps})
You need to remove it.
Plenty of problems in that SQL you posted, but you appear to be saying you will run this SQL over and over again, each time adding more IDs to exclude. Perhaps you do something that constantly discovers new IDs that should be ignored
Consider:
Where you open and close your
con
rather depends on how long it takes to work out your new ids. If it’s a few milliseconds each time, it shouldn’t be a problem to open it before the loop. If getting new IDs takes long, open the con for just the time you need it