-1

我想用 C# 命令从多个 SQL 表中删除,但总是出错:

“,”附近的语法无效。

到目前为止,这是代码:

string connectionString = @"Data Source=" + System.IO.File.ReadAllText("Server.ini") + ";" + "Initial Catalog=" + "lin2world" + ";" + "User ID=" + System.IO.File.ReadAllText("User.ini") + ";" + "Password=" + System.IO.File.ReadAllText("Password.ini");
string sql = "DELETE FROM user_data, user_item, user_ActiveSkill, user_blocklist, user_deleted, user_friend, user_henna, user_history, user_log, user_macro, user_macroinfo, user_newbie, user_nobless, user_punish, user_recipe, user_skill, user_sociality, user_subjob WHERE char_id='" + textBox1.Text + "' ";
SqlConnection connection = new SqlConnection(connectionString);
SqlDataAdapter dataadapter = new SqlDataAdapter(sql, connection);
DataSet ds = new DataSet();
connection.Open();
dataadapter.Fill(ds, "char_id");
connection.Close();
MessageBox.Show("Character Deleted!!");
4

3 回答 3

4

您只能在删除语句中从一个表中删除。

在事务中使用多个删除语句来执行删除

如果您不熟悉 C# 中的事务,这里是一个示例

using (var Conn = new SqlConnection(_ConnectionString))
{
    SqlTransaction trans = null;
    try
    {
        Conn.Open();
        trans = Conn.BeginTransaction();

        using (SqlCommand Com = new SqlCommand(ComText, Conn, trans))
        {
            /* DB work */
        }
        trans.Commit();
    }
    catch (Exception Ex)
    {
        if (trans != null) trans.Rollback();
        return -1;
    }
}
于 2013-09-27T12:03:49.970 回答
1

如果您想做类似的事情,您可以将所有表作为列表传递,仍然可以做您想做的事情。

DECLARE db_cursor CURSOR FOR  
SELECT name 
FROM master.dbo.sysdatabases 
WHERE name IN ("user_data","user_item","user_ActiveSkill","user_blocklist","user_deleted","user_friend","user_henna","user_history","user_log","user_macro","user_macroinfo","user_newbie","user_nobless","user_punish","user_recipe","user_skill","user_sociality","user_subjob")  -- use these databases

OPEN db_cursor   
FETCH NEXT FROM db_cursor INTO @name   


WHILE @@FETCH_STATUS = 0   
BEGIN   

       DELETE FROM @name WHERE char_id='whatever'

       FETCH NEXT FROM db_cursor INTO @name   
END   
编辑:似乎这些都是相关的表——如果你与 cascade:delete 有适当的关系,你应该只需要删除主记录,它的子记录都会自己处理
于 2013-09-27T12:11:44.300 回答
0

您不能在 SQL Server 的一个语句中从多个表中删除。您将需要多个语句,每个表一个:

DELETE FROM user_data WHERE PersonID = '2';
DELETE FROM user_item WHERE PersonID = '2';

等等等等

并单独关闭每一个,(确保不违反任何 FK)或创建一个存储过程并将其关闭(以最大限度地减少数据库连接的打开和关闭)。

我使用触发器的经验告诉我不要使用触发器,有时它们不会在应该触发的时候触发!

于 2013-09-27T12:18:25.600 回答