检查表或列中的SQL Server数据库表中存在 [英] Check if table or column exists in SQL Server database table
本文介绍了检查表或列中的SQL Server数据库表中存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我创造我想要检查所需的表和/或列中存在一个SQL Server数据库中的列或表。
Before I create a column or table in a SQL Server database I want to check if the required table and/or columns exist.
我寻觅了一圈,发现2路这么远。
I have searched around and found 2 ways so far.
- 存储过程,我不希望使用
- 将使用
SqlCommand.ExecuteScalar()
方法和捕获异常来确定表/列的存在,这对我来说是周围,但没有工作的完美解决方案。
- Stored procedures, which I don't want to use
- 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.
有另一种方式来检查,如果在SQL Server中存在的表/列?
Is there another way to check if table/column exists in SQL Server?
推荐答案
要检查是否架构创建之前存在,建议您执行以下操作:
To check if a schema exists before creating it, you do the following:
要检查是否存在列; 您使用 IF NOT EXISTS
,然后把你的实际查询的里面。
To check if a column exists; you use IF NOT EXISTS
and then put your actual query inside of that.
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
有关表,的查询有点类似:
IF (NOT EXISTS (SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'TheSchema'
AND TABLE_NAME = 'TheTable'))
BEGIN
CREATE TABLE MYTABLE
END
这篇关于检查表或列中的SQL Server数据库表中存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文