如果不存在,我需要添加一个特定的列。我有类似以下的内容,但它总是返回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数据库的表中是否存在列?
当前回答
select distinct object_name(sc.id)
from syscolumns sc,sysobjects so
where sc.name like '%col_name%' and so.type='U'
其他回答
首先检查dbo.syscolumns(包含字段定义的内部SQL Server表)中是否存在表/列(id/name)组合,如果不存在,则发出适当的ALTER table查询以添加它。例如:
IF NOT EXISTS ( SELECT *
FROM syscolumns
WHERE id = OBJECT_ID('Client')
AND name = 'Name' )
ALTER TABLE Client
ADD Name VARCHAR(64) NULL
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
SQL Server 2005及以后版本:
IF EXISTS(SELECT 1 FROM sys.columns
WHERE Name = N'columnName'
AND Object_ID = Object_ID(N'schemaName.tableName'))
BEGIN
-- Column Exists
END
马丁·史密斯的版本更短:
IF COL_LENGTH('schemaName.tableName', 'columnName') IS NOT NULL
BEGIN
-- Column Exists
END
调整以下内容以满足您的具体要求:
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 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