• 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.

    You are looking for something like this (i'm using a random sys table for this sample so you can copy/paste & test):

    EXEC sp_msforeachdb '

    USE [?];

    IF EXISTS (SELECT * FROM sys.schemas WHERE schema_id=1)

    BEGIN

    PRINT ''yay!''

    END';

    I was going mention that sp_msforeachdb is not documented but Sean beat me to it. There are better ways to do this - I am showing one.

    "I cant stress enough the importance of switching from a sequential files mindset to set-based thinking. After you make the switch, you can spend your time tuning and optimizing your queries instead of maintaining lengthy, poor-performing code."

    -- Itzik Ben-Gan 2001