在C#中检查SQL表是否存在 [英] Check SQL table exist or not in C#

查看:491
本文介绍了在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.


这篇关于在C#中检查SQL表是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆