2015-02-06 30 views
1

我使用下面的C#方法執行SQL查詢:如何刪除表

public bool ExecuteQurey(String pQuery) 
{ 
    SqlConnection con = new SqlConnection("MyConnectionString"); 
    con.Open(); 

    SqlTransaction trans = con.BeginTransaction(IsolationLevel.ReadCommitted); 

    try 
    { 
     SqlCommand cmd = new SqlCommand(pQuery, con, trans); 
     cmd.ExecuteNonQuery(); 
     trans.Commit(); 
     con.Close(); 
     trans.Dispose(); 
     return true; 
    } 
    catch (Exception exp) 
    { 
     trans.Rollback(); 
     con.Close(); 
     MessageBox.Show(exp.Message, "Error!!", MessageBoxButtons.OK, MessageBoxIcon.Error); 
    } 

    return false; 
} 

當我傳遞着這樣一句話:

ExecuteQuery("DROP TABLE MyTable"); 

則該方法返回true,這意味着它工作得很好,但是當我檢查SQL Server時,myTable未被刪除。如果我在SQL Server Management Studio運行相同的語句,MyTable被刪除...

我在哪裏錯了?

+2

最好的方式來創建一個存儲過程,並呼籲在C# – 2015-02-06 06:59:39

+0

附註 - 你應該看看你的資財,一旦你與他們做是爲了避免內存泄漏(任何實現IDisposable - 一些我在這裏看到的例子是SqlConnection,SqlCommand,我也相信SqlTransaction) – Bridge 2015-02-06 08:02:35

回答

4

回答你的問題,一些意見前:

  • 避免使用查詢文本編碼這樣的操作,這是一個很高的機會 你可以得到安全問題。更好地創造存儲過程 是executes table drop

    create procedure sp_DropTable 
    @tablename varchar(200) 
    as 
    BEGIN 
        DECLARE @SQL VARCHAR(MAX); 
        SET @SQL = 'IF EXISTS(SELECT 1 FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N''' + @tableName + ''') AND type = (N''U'')) DROP TABLE [' + @tableName + ']' 
    
        EXEC (@SQL); 
        END 
    GO 
    

    然後通過SP的名稱作爲參數傳遞給你的函數。現在回到你的錯誤

表中刪除不是transaction,但你嘗試在交易模式來執行它。這使它失敗。嘗試:

public bool ExecuteQurey(String pQuery) 
{ 
    SqlConnection con = new SqlConnection("MyConnectionString"); 
    con.Open(); 
    try 
    { 
     SqlCommand cmd = new SqlCommand(pQuery, con); 
     // if you pass just query text 
     cmd.CommandType = CommandType.Text; 

     // if you pass stored procedure name 
     // cmd.CommandType = CommandType.StoredProcedure; 
     cmd.ExecuteNonQuery(); 
     con.Close(); 
     return true; 
    } 
    catch (Exception exp) 
    { 
     con.Close(); 
     MessageBox.Show(exp.Message, "Error!!", MessageBoxButtons.OK, MessageBoxIcon.Error); 
    } 
    return false; 
} 
+2

sp會拋出錯誤。 '在@ tblename附近修改語法 – 2015-02-06 07:11:17

+0

1+用於更新答案 – 2015-02-06 07:19:21

+0

感謝您的評論,這對我來說真的很不明顯:/ – George 2015-02-06 07:20:16