在C#中检查SQL表是否存在

在C#中检查SQL表是否存在

问题描述:

我想检查SQL表是否存在。如果不存在,我将运行创建,如果存在,我将从该表中选择一些字段。



我尝试过:



我写这个是为了检查。但是有些错误即将出现Syantax在tempoutlet附近发生错误

低于我的代码

I want to check if the SQL table exists or not. If not exists, I will run create if exists, I will select some fields from that table.

What I have tried:

I wrote this for checking. But some error is coming that "Syantax error near tempoutlet"
below my code

bool exists;
            var chktb = new SqlCommand("select case when exists(select table_schema,table_name from information_schema.tables where schema_name='inventoryDB.mdf' and table_name='dbo.tempoutlet')", con);
            exists = (int)chktb.ExecuteScalar() == 1;



所以任何解决方案请


So any solution please

试试这个:

Try this:
SELECT CASE WHEN OBJECT_ID('dbo.MyTable', 'U') IS NOT NULL THEN 1 ELSE 0 END


我知道你已经有了一个可行的解决方案,但只是想要提供另一个。另一种方法是在try / catch中简单地执行select命令。如果表不存在,则可以使用catch块创建表。这样可以避免每次架构查找的开销。
I know you already have a working solution, but just wanted to offer another. An alternate method would be to simply execute your select command in a try/catch. If the table doesn't exist, you can use the catch block to create the table. This avoids the overhead of a schema lookup every time.