删除 SQL 表(如果存在)/创建(如果不存在)(在 C# 中)



我正在尝试创建一个 C# 方法来删除表(如果它们存在(,如果它们不存在,则创建。

到目前为止,我已经创建了一个SQL查询,该查询正在尝试删除表(如果存在(。

但是我收到此错误

System.Data.SqlClient.SqlException (0x80131904(:关键字"NULL"附近的语法不正确。

这是我的代码

static void CheckTablesExist()
{
try
{
// Build connection string
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder
{
DataSource = "WIN10-LAP-HJP",
UserID = "sa",
Password = "Mypassword123",
InitialCatalog = "SAPExtract"
};
// Connect to SQL
Console.Write("Connecting to SQL Server ... ");
using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
{
Console.WriteLine("Done.");
Console.WriteLine("Checking If table dbo.FolderInfo");
string queryCheckTable = "if object_id(@FolderTable, @FileTable) NOT NULL DROP TABLE dbo.FolderInfo ";
// string queryCheckTable = "DROP TABLE IF EXISTS @FolderTable";
using (SqlCommand command = new SqlCommand(queryCheckTable, connection))
{
command.Parameters.Add("@FolderTable", SqlDbType.NVarChar).Value = "dbo.FolderInfo";
command.Parameters.Add("@FileTable", SqlDbType.NVarChar).Value = "dbo.FileInfo";
connection.Open();
var result = command.ExecuteNonQuery();
// Check Error

}
}
}
catch (SqlException e)
{
Console.WriteLine(e.ToString());
}
}

您收到语法错误,因为您在 NOT NULL 之前缺少单词 IS。 以下 SQL 应该可以工作:

if object_id(@FolderTable, @FileTable) IS NOT NULL DROP TABLE dbo.FolderInfo

最新更新