gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 10:44:24 30 4
gpt4 key购买 nike

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

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

但是我收到这个错误

System.Data.SqlClient.SqlException (0x80131904): Incorrect syntax near the keyword '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

关于c# - 如果存在则删除 SQL 表/如果不存在则创建(在 C# 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59774431/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com