2014-07-17 16 views
1

我有一個像下面這樣的查詢,我如何從代碼(在C#中)執行它? 我可以在sql server中運行這個查詢。在.net(C#)運行查詢(創建過程)

create procedure addSystemError 
    @date Datetime, 
    @type nvarchar(50), 
    @des nvarchar(max) 
as 
    insert into SystemError values(@date,@type,@des) 
GO 


create procedure loadSystemErrorCount 
    @startDate datetime, 
    @endDate datetime, 
    @type nvarchar(50) 
as 
    if(@type='All') 
     select COUNT(*) from SystemError where date>[email protected] and date<@endDate 
    else 
     select COUNT(*) from SystemError where date>[email protected] and date<@endDate and [email protected] 
Go 
+0

我想運行一個查詢,也許在這個查詢存在比存儲過程更 – user3780058

+1

你必須把它分成兩SQL命令 - 每個'create procedure'調用一個 - 然後執行那些一個接一個。 –

+0

如果我想創建第二個過程loadSystemErrorCount,該怎麼做? – user3780058

回答

-1

這應該工作:

SqlConnection sqlConnection1 = new SqlConnection("Your Connection String"); 
SqlCommand cmd = new SqlCommand(); 

SqlDataReader reader; 

cmd.CommandText = "SELECT * FROM Customers"; 
cmd.CommandType = CommandType.Text; 
cmd.Connection = sqlConnection1; 

sqlConnection1.Open(); 

reader = cmd.ExecuteReader(); 
// Data is accessible through the DataReader object here. 

sqlConnection1.Close(); 

Microsoft how to

+2

如果答案主要是一個鏈接,評論將是足夠的.. –

+0

好的,謝謝,我會記住這個 – user3840692

+0

謝謝,我會記住這一點,並改變我的回答 – user3840692

0
using (var conn = new SqlConnection(connectionString)) 
using (var command = new SqlCommand("addSystemError", conn) { 
         CommandType = CommandType.StoredProcedure }) { 
conn.Open(); 

/* Add the parameters in command 
    .  
    . 
    . 
*/ 

command.ExecuteNonQuery(); 
conn.Close(); 
} 
+0

運行包含存儲過程的查詢,選擇....,更新... – user3780058