检查表是否存在且具有默认值

时间:2017-07-28 07:54:20

标签: sql sql-server

我可以在一个选项中进行以下2检查吗?我先检查表是否存在,然后我检查它是否有默认值。

我可以签入一个选择表是否存在且具有默认值?

IF EXISTS (SELECT 1 FROM syscolumns c WHERE c.id = OBJECT_ID('EX_EMPLOYEE') 
AND c.name = 'B_TIME')
begin
IF NOT EXISTS(select * from sys.all_columns c join sys.tables t on t.object_id = c.object_id join sys.schemas s on s.schema_id = t.schema_id
join sys.default_constraints d on c.default_object_id = d.object_id
where t.name = 'EX_EMPLOYEE' and c.name = 'B_TIME')
        BEGIN
        EXECUTE ('ALTER TABLE EX_EMPLOYEE ADD  DEFAULT 1 for B_TIME')
        END
END
GO

1 个答案:

答案 0 :(得分:0)

因此,如果您需要检查一个if子句中的两个条件,那么您可以按照以下方式执行此操作。

IF EXISTS (SELECT 1 FROM syscolumns c WHERE c.id = OBJECT_ID('EX_EMPLOYEE') 
AND c.name = 'B_TIME')
and NOT EXISTS(select * from sys.all_columns c join sys.tables t on t.object_id = c.object_id join sys.schemas s on s.schema_id = t.schema_id
join sys.default_constraints d on c.default_object_id = d.object_id
where t.name = 'EX_EMPLOYEE' and c.name = 'B_TIME')

begin
....
end