如果不存在,我需要添加一个特定的列。我有类似以下的内容,但它总是返回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数据库的表中是否存在列?
当前回答
我的一位好朋友和同事向我展示了如何在SQL Server 2005和更高版本中使用带有SQL函数OBJECT_ID和COLUMNPROPERTY的IF块来检查列。您可以使用类似于以下内容的内容:
你可以在这里看到:
IF (OBJECT_ID(N'[dbo].[myTable]') IS NOT NULL AND
COLUMNPROPERTY( OBJECT_ID(N'[dbo].[myTable]'), 'ThisColumnDoesNotExist', 'ColumnId') IS NULL)
BEGIN
SELECT 'Column does not exist -- You can add TSQL to add the column here'
END
其他回答
这在SQL Server 2000中对我有效:
IF EXISTS
(
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'table_name'
AND column_name = 'column_name'
)
BEGIN
...
END
declare @myColumn as nvarchar(128)
set @myColumn = 'myColumn'
if not exists (
select 1
from information_schema.columns columns
where columns.table_catalog = 'myDatabase'
and columns.table_schema = 'mySchema'
and columns.table_name = 'myTable'
and columns.column_name = @myColumn
)
begin
exec('alter table myDatabase.mySchema.myTable add'
+' ['+@myColumn+'] bigint null')
end
执行以下查询以检查给定表中是否存在该列:
IF(SELECT COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'TableName' AND COLUMN_NAME = 'ColumnName') IS NOT NULL
PRINT 'Column Exists in the given table';
调整以下内容以满足您的具体要求:
if not exists (select
column_name
from
INFORMATION_SCHEMA.columns
where
table_name = 'MyTable'
and column_name = 'MyColumn')
alter table MyTable add MyColumn int
这应该会奏效——仔细检查代码,找出愚蠢的错误;例如,您是否在应用插入的同一数据库上查询INFORMATION_SCHEMA?在这两个语句中,您的表/列名是否有拼写错误?
最简单易懂的解决方案之一是:
IF COL_LENGTH('Table_Name','Column_Name') IS NULL
BEGIN
-- Column Not Exists, implement your logic
END
ELSE
BEGIN
-- Column Exists, implement your logic
END