views:

38

answers:

3

I have a lengthy stored procedure that builds a query string. It works fine until I add in a 'LIKE' description field (text) which has a wildcard in it, see below:

IF @AdDescription IS NOT NULL   
    IF @AdSection IS NOT NULL
        BEGIN
            SET @SQL = @SQL + @Wand + 'na.Section = '' + @AdDescription + '''
            SET @Wand = ' AND '
        END
    ELSE
        BEGIN
            SET @SQL = @SQL + @Wand +  '(na.AdDesc LIKE ''' + @AdDescription + '%'')'
            SET @Wand = ' AND '
        END

I've tried a few variations but as soon as @AdDescription has anything in it it fails. Is there something obvious that I am missing?

+2  A: 

Try using print to see the SQl you have created, then you will likely see the error. And try really hard to avoid dynamic sql, it's hard to maintain, test, and debug properly.

Instead of exec the SQl just have it do:

Print @SQL

This will print the SQL Statement.

We usually havea debug parameter on any stored proc that uses dynamic SQl abd if it is set to 1, it prints the SQL and if it is set to 0 (the default), it executes the SQL. This makes it easier to see what is being created for a set of values later when the proc fails in production becasue of some obscure condition you didn't consider.

YOu can also get the SQl executed by running profiler, but usually it's simpler to just run with the same values in debug mode.

HLGEM
There is no other way than dynamic. How do i print the sql?
flavour404
+2  A: 

You are missing an apostrophe in your first "SET @SQL" line. There should be 3 apostrophes before you add the @AdDescription. The color coding in your code above shows this problem. The plus signs are red instead of black.

David
A: 

Edit Maybe it's just the quotes? I've added some spaces so the escaping is clearer.

IF @AdDescription IS NOT NULL
    IF @AdSection IS NOT NULL
        BEGIN
            SET @SQL = @SQL + @Wand 
                 + 'na.Section = ' ''' + @AdDescription + ''' '
            SET @Wand = ' AND '
        END
    ELSE
        BEGIN
             SET @SQL = @SQL + @Wand 
                 +  '(na.AdDesc LIKE ' ''' + @AdDescription + '%'' )'
        END
egrunin
Erm, no its not, it is used later to concatenate further info. I realize it is difficult to see this without seeing the rest of the query.
flavour404
1. What is the value of @Wand when you do SET @SQL + @Wand ?2. I just added some missing single-quotes, too.
egrunin
the @Wand start as WHERE it is only changed to AND after the first use, pretty standard pattern for dynamic sql.
Paul Creasey
It's **really** annoying that comments don't preserve formatting...
egrunin
Ah, I see. Maybe it was the quotes?
egrunin