mercredi 8 juillet 2015

exec sp_executesql in an IF stament and WHILE loop

I'm having issues with my script where it will search all tables that contains 'Dummy' in table name. I have a SELECT query where the result will be the tables that is to be deleted.

    SELECT  Row_Number() Over (Order By name) As RowNum
                        , name
                FROM    sys.all_objects
                WHERE   type = 'U'
                        and name like '%Dummy%'
                        and schema_id = @schemaID

and it returned:

    RowNum  name

    1   Dummy

    2   DummyJoinTbl1

    3   DummyJoinTbl2

    4   DummyJoinTbl3

but when I execute the below script,

    DECLARE

    @schemaName nvarchar(100),
    @schemaID int,
    @tblName nvarchar(100) = '',
    @cnt int = 1,
    @rowNumber int = 1,
    @SQL nvarchar(100)

    SET @schemaName = (select SCHEMA_NAME()) -- this is dbo
    SET @schemaID = (select SCHEMA_ID()) -- this is 1

    BEGIN

    WHILE (@cnt > 0)
        BEGIN
            SELECT @tblName = +name
            FROM 
                (
                SELECT  Row_Number() Over (Order By name) As RowNum
                        , name
                FROM    sys.all_objects
                WHERE   type = 'U'
                        and name like '%Dummy%'
                        and schema_id = @schemaID
                ) ReferenceTable    
            WHERE RowNum = @rownumber

            SET @cnt = @@ROWCOUNT
            SET @rownumber = @rownumber + 1

            IF (@cnt > 0)
            BEGIN
                PRINT 'DROP TABLE ' + @schemaName + '.' + @tblName + ' - RowCount:' + cast(@cnt as nvarchar(100))
                set @SQL = 'DROP TABLE ' + @schemaName + '.' + @tblName
                exec sp_executesql @SQL

            END

        END

        PRINT 'DONE'

    END

the result it returned:

    DROP TABLE dbo.Dummy - RowCount:1
    DROP TABLE dbo.DummyJoinTbl2 - RowCount:1
    DONE

What could have be the reason why the other tables are missed? When I removed

    set @SQL = 'DROP TABLE ' + @schemaName + '.' + @tblName
        exec sp_executesql @SQL

it will print all the tables.

    DROP TABLE dbo.Dummy - RowCount:1
    DROP TABLE dbo.DummyJoinTbl1 - RowCount:1
    DROP TABLE dbo.DummyJoinTbl2 - RowCount:1
    DROP TABLE dbo.DummyJoinTbl3 - RowCount:1
    DONE

Please do take note that the tables in the given are all empty. Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire