I have a temporary table and I need to delete a field in this temporary table if the field already exists.
I was trying using query with non temporary table and it is work, but not for temporary table.
create table #mytemp (
fieldA int null,
fieldB int null
)
IF EXISTS ( SELECT 1
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = '#mytemp'
AND COLUMN_NAME = 'fieldA'
AND TABLE_SCHEMA = 'DBO' )
BEGIN ALTER TABLE #mytemp DROP COLUMN fieldA END
You were almost there. You need to check the objects in tempdb
not the database you are connected to. Also, temporary tables have suffixes to ensure they have a unique name, so you need a LIKE
:
CREATE TABLE #mytemp (fieldA int NULL,
fieldB int NULL);
IF EXISTS (SELECT 1
FROM tempdb.INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME LIKE N'#mytemp%'
AND COLUMN_NAME = N'fieldA'
AND TABLE_SCHEMA = N'dbo' )
BEGIN
ALTER TABLE #mytemp DROP COLUMN fieldA;
END;
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.