如何将多个SQL命令组合为一个?

时间:2018-10-24 11:16:42

标签: c# sql wpf

是否可以通过将以下查询合并到单个SQLCommand中来优化它们?

SqlCommand cmd = new SqlCommand
{
    CommandType = CommandType.Text,
    CommandText = "DELETE FROM cbu_naslovi WHERE [ID]='" + CurrentID + "'",
    Connection = con
};
SqlCommand cmd1 = new SqlCommand
{
    CommandType = CommandType.Text,
    CommandText = "DELETE FROM cbu_deli WHERE [IDX]='" + CurrentID + "'",
    Connection = con
};
cmd.ExecuteNonQuery();
cmd1.ExecuteNonQuery();

编辑:社区建议的可行解决方案在下面

SqlCommand cmd = new SqlCommand
{
    CommandType = CommandType.Text,
    CommandText = "DELETE FROM cbu_naslovi WHERE [ID] = @CurrentID; DELETE FROM cbu_deli WHERE [IDX] = @CurrentID",
    Connection = con
};
cmd.Parameters.AddWithValue("@CurrentID", CurrentID);
cmd.ExecuteNonQuery();

3 个答案:

答案 0 :(得分:4)

Yes, you can just separate them with a semicolon. For example I have code that executes the following in a single call

SET NOCOUNT ON;
DECLARE @decimalDate DECIMAL(12,0);
DECLARE @charDate CHAR(12);
DECLARE @utcDate DATETIMEOFFSET;
DECLARE date_cursor CURSOR FOR SELECT {1} FROM {0} WHERE ISNULL({1},0)!=0;
OPEN date_cursor;
FETCH NEXT FROM date_cursor INTO @decimalDate;
WHILE @@FETCH_STATUS=0
BEGIN
    BEGIN TRY SET @charDate=CONVERT(CHAR(12),@decimalDate);
        SET @utcDate=SwitchOffset(
                CONVERT(DATETIME,'20'
                    +SUBSTRING(@charDate,1,2)+'-'+SUBSTRING(@charDate,3,2)+'-'
                    +SUBSTRING(@charDate,5,2)+' '+SUBSTRING(@charDate,7,2)+':'
                    +SUBSTRING(@charDate,9,2)+':'+SUBSTRING(@charDate,11,2)
                ,121) AT TIME ZONE '{3}',0);
    END
    TRY BEGIN CATCH
        SET @utcDate=SysUtcDateTime();
    END CATCH;
    BEGIN
        TRY UPDATE {0} SET {2}=@utcDate WHERE CURRENT OF date_cursor;
    END TRY
    BEGIN CATCH END CATCH;
    FETCH NEXT FROM date_cursor INTO @decimalDate;
END;
CLOSE date_cursor;
DEALLOCATE date_cursor;

There are exceptions. For instance the "create procedure" statement must be the first statement of a block. But most DML can be batched like this.

答案 1 :(得分:1)

You can write it like this:

SqlCommand cmd = new SqlCommand
{
    CommandType = CommandType.Text,
    CommandText = $"DELETE FROM cbu_naslovi WHERE [ID]='{CurrentID}';DELETE FROM cbu_deli WHERE [IDX]='{CurrentID}'",
    Connection = con
};

答案 2 :(得分:0)

如果您需要运行“非查询”操作,则可以尝试使用Server对象执行一堆命令。 好处:您可以在SQL语句中使用GOCommand不允许使用GO

server.ConnectionContext.ExecuteNonQuery("your SQL statement -- could be 100 statements with hundrends of GO commands", ExecutionTypes.Default)

服务器变量的类型为Server