关于sql:检查表中是否存在列

Check Column Exist in a Table

如何使用SQL查询检查表中是否存在列?我正在使用Access 2007。


您可以使用信息模式视图:

1
2
3
4
5
6
7
8
9
IF NOT EXISTS (SELECT Column_Name
               FROM INFORMATION_SCHEMA.COLUMNS
               WHERE TABLE_NAME = 'YourTable'
               AND Column_Name = 'YourColumn')
BEGIN

-- Column doesn't exist

END

此外,您可能希望通过包括数据库和/或模式来进一步限制where子句。

1
2
3
4
5
6
7
8
9
10
11
12
IF NOT EXISTS (SELECT Column_Name
               FROM INFORMATION_SCHEMA.COLUMNS
               WHERE TABLE_NAME = 'YourTable'
               AND Column_Name = 'YourColumn'
               AND Table_Catalog = 'YourDatabaseName'
               AND Table_Schema = 'YourSchemaName')

BEGIN

-- Column doesn't exist

END


1
2
3
4
5
6
7
8
9
IF NOT EXISTS (SELECT 1
FROM syscolumns sc
JOIN sysobjects so
ON sc.id = so.id
WHERE so.Name = 'TableName'
AND sc.Name = 'ColumnName')
BEGIN
--- do your stuff
END


1
2
3
4
5
6
7
8
IF EXISTS(SELECT * FROM sys.columns WHERE Name = N'columnName'  
            AND Object_ID = Object_ID(N'tableName'))

BEGIN

    -- Column Exists

END

"参考"