简体   繁体   中英

T-SQL drop multiple tables error subquery returned more than 1 value

I have the below T-SQL to drop tables where their name exists in tblCtrlTable :

Declare @Cmd nvarchar(max)

select @cmd = ( 
SELECT 'IF OBJECT_ID(''' +TABLE_NAME + ''') IS NOT NULL BEGIN DROP TABLE [' + TABLE_NAME + '] END;' 
FROM INFORMATION_SCHEMA.TABLES 
WHERE TABLE_NAME IN (SELECT [TEST_TABLE] from tblCtrlTable WHERE FieldX=1 and FieldY = 'Pass'))

print @cmd

--EXECUTE sp_executesql @cmd

However, I keep getting the error:

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

Where am I going wrong?

Here is one way you do this. It doesn't ensure the order of values but it is super quick and easy. Not really sure why you are checking if the object_id is valid though....it can't be NULL because it is a table. And you know it is a table because you are querying INFORMATION_SCHEMA.TABLES. :)

Declare @Cmd nvarchar(max) = '' --Notice this is initially set to an empty string.

select @cmd = @cmd + 'IF OBJECT_ID(''' +TABLE_NAME + ''') IS NOT NULL BEGIN DROP TABLE [' + TABLE_NAME + '] END;' 
FROM INFORMATION_SCHEMA.TABLES 
WHERE TABLE_NAME IN (SELECT [TEST_TABLE] from tblCtrlTable WHERE FieldX=1 and FieldY = 'Pass')

print @cmd

Try Table variable instead of variable:

Declare @Cmd TABLE (QUERY nvarchar(max))

INSERT INTO @Cmd(QUERY)
SELECT
            'IF OBJECT_ID(''' + TABLE_NAME + ''') IS NOT NULL BEGIN DROP TABLE [' + TABLE_NAME + '] END;'
        FROM INFORMATION_SCHEMA.TABLES
        WHERE TABLE_NAME IN (SELECT
                [TEST_TABLE]
            FROM tblCtrlTable
            WHERE FieldX = 1
            AND FieldY = 'Pass')


SELECT * FROM @cmd

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM