如果不存在,我需要添加一个特定的列。我有类似以下的内容,但它总是返回false:
IF EXISTS(SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'myTableName'
AND COLUMN_NAME = 'myColumnName')
如何检查SQL Server数据库的表中是否存在列?
如果不存在,我需要添加一个特定的列。我有类似以下的内容,但它总是返回false:
IF EXISTS(SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'myTableName'
AND COLUMN_NAME = 'myColumnName')
如何检查SQL Server数据库的表中是否存在列?
当前回答
如果列不存在,请执行以下操作:
BEGIN
IF (COL_LENGTH('[dbo].[Table]', 'Column ') IS NULL)
BEGIN
// Do something
END
END;
如果列确实存在,请执行以下操作:
BEGIN
IF (COL_LENGTH('[dbo].[Table]', 'Column ') IS NOT NULL)
BEGIN
// Do something
END
END;
其他回答
试试这个。。。
IF NOT EXISTS(
SELECT TOP 1 1
FROM INFORMATION_SCHEMA.COLUMNS
WHERE
[TABLE_NAME] = 'Employees'
AND [COLUMN_NAME] = 'EmployeeID')
BEGIN
ALTER TABLE [Employees]
ADD [EmployeeID] INT NULL
END
IF EXISTS (
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_CATALOG = 'Database Name'
and TABLE_SCHEMA = 'Schema Name'
and TABLE_NAME = 'Table Name'
and COLUMN_NAME = 'Column Name'
and DATA_TYPE = 'Column Type') -- Where statement lines can be deleted.
BEGIN
-- Column exists in table
END
ELSE BEGIN
-- Column does not exist in table
END
我更喜欢INFORMATION_SCHEMA.COLUMNS而不是系统表,因为Microsoft不保证在不同版本之间保留系统表。例如,dbo.syscolumns在SQL Server 2008中仍然有效,但它已被弃用,将来可以随时删除。
Wheat的答案很好,但它假设您在任何模式或数据库中都没有任何相同的表名/列名对。为了确保安全,使用这个。。。
select *
from Information_Schema.Columns
where Table_Catalog = 'DatabaseName'
and Table_Schema = 'SchemaName'
and Table_Name = 'TableName'
and Column_Name = 'ColumnName'
这在SQL Server 2000中对我有效:
IF EXISTS
(
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'table_name'
AND column_name = 'column_name'
)
BEGIN
...
END