• zilla (12/17/2012)


    I have a sub query within my IF statement that evaluates to one single number that I am using for a comparison operator. I am thinking there is something wrong with my syntax in my IF statement because I am not getting any results.

    Here is the code snippet.

    IF('USE ' +@DB_Name+ '

    SELECT version_number

    FROM '+ ''+@DB_Name+ '' +'.dbo.schema_version') LIKE '4.%'

    BEGIN

    ...stuff to do

    END

    If I change my IF to PRINT it says: Incorrect syntax near the keyword 'LIKE'.

    Any ideas why this might be failing?

    Thanks.

    There are so many things wrong here it is hard to know where to start.

    First you are using an IF statement with no condition. Almost like you are thinking that somehow a string will automagically get executed if it in a IF. All you have is a string and you are trying to somehow add the LIKE condition to a string or something. Also, there is no reason to add the Use @DBName because you are fully qualifying the database in the query. 😉

    What you need to do is use the EXISTS condition. I am not quite sure why you have to dynamically check the database here. Is this part of an update script and you want to do something to each database if the version is like 4. or something along those lines?

    If you can explain what you are trying to do this should be pretty straight forward.

    _______________________________________________________________

    Need help? Help us help you.

    Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.

    Need to split a string? Try Jeff Modens splitter http://www.sqlservercentral.com/articles/Tally+Table/72993/.

    Cross Tabs and Pivots, Part 1 – Converting Rows to Columns - http://www.sqlservercentral.com/articles/T-SQL/63681/
    Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs - http://www.sqlservercentral.com/articles/Crosstab/65048/
    Understanding and Using APPLY (Part 1) - http://www.sqlservercentral.com/articles/APPLY/69953/
    Understanding and Using APPLY (Part 2) - http://www.sqlservercentral.com/articles/APPLY/69954/