Home Forums SQL Server 2012 SQL Server 2012 - T-SQL Dynamic SQL Query Not Fetching Records based on where Not In condition RE: Dynamic SQL Query Not Fetching Records based on where Not In condition

  • Luis Cazares - Monday, July 24, 2017 6:46 AM

    This code is wildly open to SQL injection. If you don't know what I'm talking about, please google it.
    Scratch that.
    This code has no reason to be dynamic. It also has no reason to use NOT IN.
    It just needs a simple approach:
    SELECT title, titleofcourtesy FROM employees WHERE employeeid <> @employeeid;

    Now, if the code is more complex that what you have shown in here, unscratch the first part and read about SQL injection.

    The more I think about this, the more convinced I become that the intent of having NOT IN as part of the query was that someone was going to provide a list of employee ID values, and that the idea of using dynamic SQL was predicated on that being a comma delimited list of integers.   Of course, that's a particularly bad idea given the potential for SQL injection, for any kind of site that faces the world wide web, as just a few extra lines of code provided in an input line could then be a serious problem.   There's a fairly straightforward way to turn the ID values into a table and have a stored procedure use a parameter that is a table, which would then eliminate the need for any dynamic SQL.

    Steve (aka sgmunson) 🙂 🙂 🙂
    Rent Servers for Income (picks and shovels strategy)