我希望以下代码检查数据库中是否存在表,如果不存在则创建表。如果“ exists” == 0,则不存在;如果“ exists” = 1 ,,则存在。运行此代码后,“存在”仍然==0。我缺少什么?谢谢:
编辑:只要我跳过“ command.ExecuteNonQuery()”,就会引发错误。
var dif = new DataInterfaceFactory(DatabaseTypes.SqlServer, "WDM_SOFTWARE_INFO", "d2sql4.d2.wdm");
using (DataReader dr = dif.GetDataReader())
{
dr.ExecuteReader("SELECT COUNT(1) AS TABLECOUNT FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'CALCULATION_SCHEDULE'");
while (dr.Read())
{
var exists = Convert.ToInt32(dr["TABLECOUNT"]);
if (exists == 0)
{
var conStr = "Data Source = d2sql4.d2.wdm; Integrated Security = True; Connect Timeout = 30; Encrypt = False; TrustServerCertificate = False; ApplicationIntent = ReadWrite; MultiSubnetFailover = False";
using (SqlConnection con = new SqlConnection(conStr))
{
try
{
// Open the SqlConnection.
con.Open();
// The following code uses an SqlCommand based on the SqlConnection.
using (SqlCommand command = new SqlCommand("CREATE WDM_SOFTWARE_INFO.CALCULATION_SCHEDULE(CALCULATION_SCHEDULE_UID INT,SERVER_NAME char(25),DATATABLE_NAME char(20),LAST_CHECK_DATE DATE,IS_RUNNING INT);", con))
command.ExecuteNonQuery();
}
catch
{
Console.WriteLine("Error: could not create CALCULATION_SCHEDULE");
}
}
}
}
}
答案 0 :(得分:0)
这是我的问题的解决方案:
var dif = new DataInterfaceFactory(DatabaseTypes.SqlServer, "WDM_SOFTWARE_INFO", "d2sql4.d2.wdm");
using (DataReader dr = dif.GetDataReader())
{
dr.ExecuteReader("SELECT COUNT(1) AS TABLECOUNT FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'CALCULATION_SCHEDULE'");
var exists = Convert.ToInt32(dr["TABLECOUNT"]);
CommandExecutor CE = dif.GetCommandExecutor();
try
{
if (exists == 0)
{
string sql = "CREATE TABLE dbo.CALCULATION_SCHEDULE(CALCULATION_SCHEDULE_UID INT,SERVER_NAME char(25),DATATABLE_NAME char(20),LAST_CHECK_DATE DATE,IS_RUNNING INT)";
CE.ExecuteNonQuery(sql);
}
}
catch (Exception ex)
{
Console.WriteLine("Error: could not create CALCULATION_SCHEDULE");
}
}
答案 1 :(得分:0)
]测试它,这是检查的好方法。确保ConnectionStrig的一部分
var conStr = @"data source=d2sql4.d2.wdm\nkdes;initial catalog=WDM_SOFTWARE_INFO;MultipleActiveResultSets=True;Connect Timeout = 30; Encrypt = False; TrustServerCertificate = False; ApplicationIntent = ReadWrite; MultiSubnetFailover = False";
var existQuery = @"SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_NAME = 'CALCULATION_SCHEDULE'";
var createQuery = "CREATE TABLE [CALCULATION_SCHEDULE](CALCULATION_SCHEDULE_UID INT,SERVER_NAME char(25),DATATABLE_NAME char(20),LAST_CHECK_DATE DATE,IS_RUNNING INT)";
SqlConnection con = new SqlConnection(conStr);
if(con.State == System.Data.ConnectionState.Closed)
con.Open();
var sqlCmd = new SqlCommand(existQuery, con);
var dr = sqlCmd.ExecuteReader();
if (!dr.HasRows)
{
sqlCmd.CommandText = createQuery;
sqlCmd.ExecuteNonQuery();
}
else
Console.WriteLine("your message");