[英]ExecuteNonQuery and Return Value from SQL Server, C#
我想為用戶提供Web服務,以便用戶在表中插入或更新某些值。 用戶輸入一個ID和三個參數。 如果該ID在數據庫中不存在,我想返回0,則失敗或類似。 當我測試下面的代碼並提供一個不存在的ID時,存儲過程返回1的單元格(返回值)為0,但狀態設置為1。我猜這是因為我在執行查詢時使用ToString()並返回1個單元格。 那么我應該如何改進下面的代碼?
我在方法中有此代碼:
string status = "";
SqlParameter[] param = {
new SqlParameter("@ID", ID),
new SqlParameter("@Flag", Flag),
new SqlParameter("@C_Interval", C_Interval),
new SqlParameter("@D_Interval", D_Interval)
};
status = DatabaseHelper.ExecuteNonQuery("sp_InsertInstruction", param);
return status;
在ExecuteNonQuery中,我將存儲過程命令傳遞給數據庫
// skipped some of the code this example
status = cmd.ExecuteNonQuery().ToString();
return status;
我的存儲過程如下所示:
ALTER PROCEDURE dbo.sp_InsertInstruction
@Flag char(1) = null,
@C_Interval int=null,
@D_Interval int=null,
@ID char(20),
AS
DECLARE @Entity_ID int
SET @Entity_ID = (SELECT ID FROM Entity WHERE ID = @ID)
INSERT INTO Instructions(Flag, C_Interval, D_Interval, Entity_ID)
VALUES (@Flag, @C_Interval, @D_Interval, @Entity_ID)
提前致謝。
ExecuteNonQuery返回受影響的行數。 在這種情況下,您總是要插入一行。
更改您的SP以讀取如下內容:
ALTER PROCEDURE dbo.sp_InsertInstruction
@Flag char(1) = null,
@C_Interval int=null,
@D_Interval int=null,
@ID char(20),
AS
DECLARE @Entity_ID int
SET @Entity_ID = (SELECT ID FROM Entity WHERE ID = @ID)
IF (@Entity_ID IS NOT NULL)
BEGIN
INSERT INTO Instructions(Flag, C_Interval, D_Interval, Entity_ID)
VALUES (@Flag, @C_Interval, @D_Interval, @Entity_ID)
END
即只有在實體ID確實存在時才插入。
將此代碼放在存儲過程的頂部
ALTER PROCEDURE dbo.sp_InsertInstruction
@Flag char(1) = null,
@C_Interval int=null,
@D_Interval int=null,
@ID char(20),
AS
IF NOT EXISTS
(
SELECT ID
FROM Entity
WHERE ID = @ID
)
BEGIN
RETURN 0;
END
-- Your remaining SQL Code here....
被顯示為“ 1”的返回值是執行查詢后返回的總行數。
這是您可能需要做的事情的草稿,這只是關於如何在代碼中處理過程數據的想法。 而且我正在修改您的sql過程以返回您期望返回的值。
對於后面的代碼:
using System.Data.SqlClient;
using System.Data;
public class DBAccess{
private string strCon = "Data Source=YourServer;Initial Catalog=YourDBName;etc";
public string GetResult(){
string strQuery = "Exec YourProcedure Param1";
SqlCommand cmdSql = new SqlCommand(strQuery);
SqlConnection conSql = new SqlConnection(strCon);
conSql.Open();
cmdSql.Connection=conSql;
SqlDataReader dreSql = cmdSql.ExecuteReader();
dreSql.Read();
// here I'm trying to read the item of the row on the column named Result
return dreSql["Result"].ToString();
}
}
您的程序:
ALTER PROCEDURE dbo.sp_InsertInstruction
@Flag char(1) = null,
@C_Interval int=null,
@D_Interval int=null,
@ID char(20) AS
DECLARE @Entity_ID int
SET @Entity_ID = (SELECT ID FROM Entity WHERE ID = @ID)
if(@Entity_ID is not null)
begin
INSERT INTO Instructions(Flag, C_Interval, D_Interval, Entity_ID)
VALUES (@Flag, @C_Interval, @D_Interval, @Entity_ID)
-- this will return as a table with the result of 1
select Result='1'
end
else
begin
-- this will return as a table with the result of 0
select Result='0'
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.