简体   繁体   English

检查SQL Server数据库表中是否存在表或列

[英]Check if table or column exists in SQL Server database table

Before I create a column or table in a SQL Server database I want to check if the required table and/or columns exist. 在SQL Server数据库中创建列或表之前,我想检查所需的表和/或列是否存在。

I have searched around and found 2 ways so far. 我到处搜索并找到2种方法。

  1. Stored procedures, which I don't want to use 存储过程,我不想使用
  2. By using the SqlCommand.ExecuteScalar() method and catching an exception to determine if the table/column exists, which for me is a work around but not a perfect solution. 通过使用SqlCommand.ExecuteScalar()方法并捕获异常以确定表/列是否存在,这对我来说是一个变通方法,但不是一个完美的解决方案。

Is there another way to check if table/column exists in SQL Server? 还有另一种方法检查SQL Server中是否存在表/列吗?

To check if a schema exists before creating it, you do the following: 要在创建架构之前检查其是否存在,请执行以下操作:

To check if a column exists; 检查是否存在一列; you use IF NOT EXISTS and then put your actual query inside of that. 您使用IF NOT EXISTS ,然后将实际查询放入其中。

IF NOT EXISTS(SELECT * FROM sys.columns 
        WHERE [name] = N'columnName' AND [object_id] = OBJECT_ID(N'tableName'))
BEGIN
    ALTER TABLE ADD COLUMN MYCOLUMN
END

For a table, the query is a little similar : 对于表, 查询有点类似

IF (NOT EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                 WHERE TABLE_SCHEMA = 'TheSchema' 
                 AND  TABLE_NAME = 'TheTable'))
BEGIN
    CREATE TABLE MYTABLE
END

Query against the information_schema views : 查询information_schema视图

select * 
from information_schema.columns
where column_name = @mycolumn
    and table_name = @mytable

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM