如果表不存在,我该如何创建表? [英] How do I create a table if it doesnt exist?

查看:95
本文介绍了如果表不存在,我该如何创建表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究ac #project,现在我需要在sql中创建一个表,但是如果它不存在我只需要创建它。



我尝试了什么:



我在google上搜索并找到了这个,但由于某种原因无法正常工作,这会忽略

I'm working on a c# project and now I need to create a table in sql,but I just need to create it if it doesnt exist.

What I have tried:

I did a search on google and found this, but for some reason isnt working, this ignores the

if

并且只是创建表格,如果表格已经存在,它会跳过我的所有代码,但我没有收到任何错误

and just creates the table and if the table already exist it skips all my code, but I get no error

conn.Open();
SqlCommand command = new SqlCommand("IF OBJECT_ID('UXMenu', 'U') IS NULL CREATE TABLE UXMenu(TransDocument char(10), TransSerial char(8), TransDocNumber float, PartyName char(75), PartyLocalityID char(5), TotalAmount char (25), ShipToPostalCode char(50), Estado int);", conn);
command.ExecuteNonQuery();
MessageBox.Show("tabela criada");
conn.Close();

推荐答案

嗯。您确实注意到您的命令检查了一个表,如果它不存在,则会创建一个名称完全不同的表吗?

Um. You did notice that your command checks for one table, and if it doesn't exist creates a table with a totally different name?
IF OBJECT_ID('UXFaturas', 'U') IS NULL CREATE TABLE UXMenu(...);





如果它被纠正,那么如果它找到了表,则没有任何错误。如果确实存在错误,您可以添加错误:



And if it is corrected, then if it finds the table or not there is nothing to error. You could add an error if it does exist:

IF OBJECT_ID('UXMenu', 'U') IS NULL 
   CREATE TABLE UXMenu(TransDocument char(10), TransSerial char(8), TransDocNumber float, PartyName char(75), PartyLocalityID char(5), TotalAmount char (25), ShipToPostalCode char(50), Estado int);
ELSE 
   THROW 50001, 'Table Exists', 1;


这篇关于如果表不存在,我该如何创建表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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