Eliminate Dynamic SQL - WHERE Clause

  • I have code using dynamic SQL that has dynamic SQL because of changing WHERE Clause. I want to eliminate dynamic SQL and use static SQL instead. But my new code does not return any rows. I am unable to set column name on left side of WHERE clause. Is what I am doing even possible?

    Thanks in advance!

    ----- Table DDL script with data

    CREATE TABLE dbo.TEST

    (

    CUSTOMER_ID VARCHAR(10)

    , FIRST_NAME VARCHAR(60)

    , LAST_NAME VARCHAR(60)

    )

    INSERT INTO dbo.TEST (CUSTOMER_ID, FIRST_NAME, LAST_NAME)

    VALUES

    ('0000000001', 'JOHN', 'SMITH')

    , ('0000000002', 'JANE', 'SMITH')

    , ('0000000003', 'JACK', 'FROST')

    , ('0000000004', 'KEVIN', 'SMITH')

    , ('0000000005', 'DAN', 'BATES')

    , ('0000000006', 'RICHARD', 'WANG')

    , ('0000000007', 'REBECCA', 'BLUE')

    , ('0000000008', 'LAUREN', 'LOCKS')

    , ('0000000009', 'NANCY', 'GOLDEN')

    , ('0000000010', 'TONY', 'DANZA')

    -----Existing Dynamic SQL - works

    DECLARE

    @SQL VARCHAR(1000)

    , @WHERE_CLAUSE VARCHAR(200) = 'CUSTOMER_ID = ''0000000008'''

    SELECT

    @SQL = '

    SELECT

    *

    FROM

    dbo.TEST'

    -----WHERE Clasue

    IF @WHERE_CLAUSE IS NOT NULL

    SELECT

    @SQL = @SQL

    + '

    WHERE

    ' + @WHERE_CLAUSE

    EXECUTE (@SQL)

    GO

    ----- Want to do

    -- This works

    DECLARE

    @SQL VARCHAR(1000)

    , @WHERE_CLAUSE VARCHAR(200) = 'CUSTOMER_ID = 0000000008'

    SELECT

    *

    FROM

    dbo.TEST AS C

    WHERE

    CUSTOMER_ID = (

    CASE

    WHEN @WHERE_CLAUSE IS NOT NULL

    THEN LTRIM(RTRIM(SUBSTRING(@WHERE_CLAUSE, PATINDEX('%=%', @WHERE_CLAUSE)+1, LEN(@WHERE_CLAUSE))))

    ELSE '1'

    END)

    -- Not working

    SELECT

    *

    FROM

    dbo.TEST AS C

    WHERE

    (CASE

    WHEN @WHERE_CLAUSE IS NOT NULL

    THEN LTRIM(RTRIM(SUBSTRING(@WHERE_CLAUSE, 1, PATINDEX('%=%', @WHERE_CLAUSE)-1)))

    ELSE '1'

    END

    ) = (

    CASE

    WHEN @WHERE_CLAUSE IS NOT NULL

    THEN LTRIM(RTRIM(SUBSTRING(@WHERE_CLAUSE, PATINDEX('%=%', @WHERE_CLAUSE)+1, LEN(@WHERE_CLAUSE))))

    ELSE '1'

    END)

  • You can't "set a column name" without using dynamic SQL. You can use a CASE expression to choose between two column VALUES, but this could very well cause performance problems. Why do you want to avoid dynamic SQL ??

    __________________________________________________

    Against stupidity the gods themselves contend in vain. -- Friedrich Schiller
    Stop, children, what's that sound? Everybody look what's going down. -- Stephen Stills

  • Thanks for your response. This particular bit of dynamic sql code was part of a much bigger part of dynamic sql infested code. I was able to get rid of the rest of the dynamic sql logic except this.

    This has made the code I am working on much easier to read and comprehend.

    Oh well, I guess I will have to live with this one bit of dynamic sql code!

  • dynamic sql is also more susceptible to sql injection. you might find it cleaner to have 2 queries with different formatted where clauses and an if statement that chooses which sql statement to run.

  • getoffmyfoot (10/5/2010)


    dynamic sql is also more susceptible to sql injection. you might find it cleaner to have 2 queries with different formatted where clauses and an if statement that chooses which sql statement to run.

    If correctly done, dynamic SQL is not susceptible to SQL injection.

    You just have to make sure the code is correctly parameterized, and that input from the application is not used directly to build SQL statements.

  • Agreed. Parameterized dynamic SQL using sp_executesql not only prevents SQL injection attacks, it also provides for execution plan caching.

    __________________________________________________

    Against stupidity the gods themselves contend in vain. -- Friedrich Schiller
    Stop, children, what's that sound? Everybody look what's going down. -- Stephen Stills

  • Thanks all. That is what I will do...

  • You're welcome Vishal. But looking at your "working" example, what you are doing isn't really dynamic SQL at all. You are assigning a long string value to your @WHERE_CLAUSE variable and then just eliminating the equal sign and everything to the left. The " Customer_ID = " isn't necessary at all in the value of @WHERE_CLAUSE. The actual test against the customer column is being done expressly in your where clause, not dynamic at all. You might as well just start out assigning it a value of 8.

    DECLARE

    @CUSTID VARCHAR(20) = '0000000008'

    SELECT *

    FROM dbo.TEST AS C

    WHERE CUSTOMER_ID = isnull(@CUSTID,1)

    __________________________________________________

    Against stupidity the gods themselves contend in vain. -- Friedrich Schiller
    Stop, children, what's that sound? Everybody look what's going down. -- Stephen Stills

  • Well using CUSTOMER_ID is one column they will use in the where clause. In actual scenario, the existing code may have a where clause for some other column - that's how the existing code is! it may as well be FIRST_NAME = 'xxx'

  • Perhaps I'm not explaining clearly enough.

    The comparison to the customer ID is hard coded in the WHERE clause. It has nothing to do with the "Customer_ID = " that you initially put in the @WHERE_CLAUSE variable, because you are parsing that out.

    You can change the value of @WHERE_CLAUSE to start with "ANYCOLUMN = 0000000008" and the comparison will still be done against the Customer_ID column.

    Try altering the second line of your code and see.

    -- This works and will always work, but only as a test against the customer_id

    DECLARE

    @SQL VARCHAR(1000)

    , @WHERE_CLAUSE VARCHAR(1000) = 'NOTHING TO THE LEFT OF THE EQUAL SIGN MATTERS = 0000000008'

    SELECT

    *

    FROM

    dbo.TEST AS C

    WHERE

    CUSTOMER_ID = (

    CASE

    WHEN @WHERE_CLAUSE IS NOT NULL

    THEN LTRIM(RTRIM(SUBSTRING(@WHERE_CLAUSE, PATINDEX('%=%', @WHERE_CLAUSE)+1, LEN(@WHERE_CLAUSE))))

    ELSE '1'

    END)

    __________________________________________________

    Against stupidity the gods themselves contend in vain. -- Friedrich Schiller
    Stop, children, what's that sound? Everybody look what's going down. -- Stephen Stills

  • Sorry for the confusion. In the snippet that I marked as "Want to Do -- This works" I was merely showing an example where using PATINDEX for the right side of equal to side worked.

    But my actual code that I want working is flagged under "Not working" where both are wildcards - the column name and also the comparison for the column name so the where clause can be:

    WHERE

    CUSTOMER_ID = 'XXX'

    or...

    WHERE

    FIRST_NAME = 'ZZZ'

  • @Dixie is right( Because in your first case the where clause is stripped down to remove the column name totally)

    I dont think you will be able to use column names assigned to variables and then just do a CASE statement wrap around to select

    that particular column. I think that is the the work of Dynamic SQL and if you use the following code in its original form i.e. without the @WHere1 and @where2 variables unassigned it also doesnt work.

    DECLARE @SQL NVARCHAR(MAX)

    DECLARE @WHERE_CLAUSE NVARCHAR(200) = 'CUSTOMER_ID = 0000000008'

    DECLARE @WHERE1 NVARCHAR(MAX)

    DECLARE @WHERE2 NVARCHAR(MAX)

    DECLARE @PAram NVARCHAR(MAX)

    SET @Param = N'@s_WHERE_CLAUSE VARCHAR(200) '

    SELECT @WHERE1 = LTRIM(RTRIM(SUBSTRING(@WHERE_CLAUSE, 1, PATINDEX('%=%', @WHERE_CLAUSE)-1)))

    SELECT @WHERE2 = LTRIM(RTRIM(SUBSTRING(@WHERE_CLAUSE, PATINDEX('%=%', @WHERE_CLAUSE)+1, LEN(@WHERE_CLAUSE))))

    SET @SQL = N'SELECT *

    FROM

    dbo.TEST AS C

    WHERE

    (CASE

    WHEN @s_WHERE_CLAUSE IS NOT NULL

    THEN ' + @WHere1 + ' ELSE ''1'' END

    ) = (

    CASE

    WHEN @s_WHERE_CLAUSE IS NOT NULL

    THEN '+ @WHERE2 +' ELSE ''1'' END)'

    SELECT @SQL

    EXEC SP_EXECUTESQL @SQL, @param , @s_WHERE_CLAUSE = @WHERE_CLAUSE

    SO in that case selecting a column name has to be done dynamically which is the actual purpose of DSQL.Please see the attached a code if you actually want to use it as DSQL.

  • The good news is that when you do parameterized dynamic SQL, it can take advantages of existing indexes and views, and even cache a query plan for future use by similar queries. As I said, you can use a CASE Statement to match on different columns BUT this approach is certain to result in a table scan execution plan and is therefore totally unsuitable for any production volumes. I am attaching the code as a curiosity, but I strongly advise you to AVOID this approach. Let us know if you need any help coming up with a dynamic SQL solution. 🙂

    __________________________________________________

    Against stupidity the gods themselves contend in vain. -- Friedrich Schiller
    Stop, children, what's that sound? Everybody look what's going down. -- Stephen Stills

Viewing 13 posts - 1 through 12 (of 12 total)

You must be logged in to reply to this topic. Login to reply