2011-11-21 69 views
3

我想知道如何一次執行多個SQL命令。如何在c#中執行超過1行的sql命令

此時此刻我正在做這樣的:

using (SqlConnection sqlConnection1 = new SqlConnection(connectionString)) 
{ 
    using (SqlCommand cmd = new SqlCommand()) 
    { 
     cmd.CommandText = "SELECT nome FROM teste"; 
     cmd.CommandType = CommandType.Text; 
     cmd.Connection = sqlConnection1; 

     sqlConnection1.Open(); 

     // execute the command 
     SqlDataReader rdr = cmd.ExecuteReader(); 
     while (rdr.Read()) 
     { 
      listBox1.Items.Add(rdr["name"].ToString()); 
     } 
    } 
} 

但我該怎麼做才能執行

use [databaseX] 
SELECT nome FROM teste 
在我的C#程序

+2

您不需要執行該行;你可以在'connectionString'中設置你想要使用的數據庫。 –

回答

4

單獨用分號(;)多個語句。 (順便說一句,一般不需要use語句,因爲它是你的連接字符串中設置。)

3

使用@申報字符串:

cmd.CommandText = @" 
    use [databaseX] 
    SELECT nome FROM teste 
"; 

或實際逃脫換行符:

cmd.CommandText = "use [databaseX]\nSELECT nome FROM teste"; 
3

SQL使用;到單獨的命令/查詢。

SELECT * FROM Table1; SELECT * FROM Table2; 

產生結果集。