CREATE PROCEDURE dbo.GetUserList
AS
BEGIN
SELECT UserID, UserName FROM Users ORDER BY UserID DESC;
END
public static string GetUserList(ref ArrayList names, ref ArrayList ids)
{
using (SqlConnection conn = ADConnection.CreateConnection())
using (SqlCommand cmd = new SqlCommand("GetUserList", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
conn.Open();
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
if (!string.IsNullOrEmpty(dr[0].ToString()))
ids.Add(dr[0].ToString());
names.Add(dr[1].ToString());
}
}
return "OK";
}
}
關鍵點:將 CommandType 設為 StoredProcedure,命令文字僅需程序名稱。
CREATE PROCEDURE dbo.GetCommentsByDateRange
@StartDate VARCHAR(16),
@EndDate VARCHAR(16)
AS
BEGIN
SELECT ID FROM Table_AX
WHERE CommentDateTime > @StartDate AND CommentDateTime < @EndDate
ORDER BY ContentOwnerID DESC;
END
public static string GetComments(string startDate, string endDate, ref DataSet ds)
{
using (SqlConnection conn = ADConnection.CreateConnection())
using (SqlDataAdapter da = new SqlDataAdapter("GetCommentsByDateRange", conn))
{
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.Parameters.AddWithValue("@StartDate", startDate);
da.SelectCommand.Parameters.AddWithValue("@EndDate", endDate);
try
{
conn.Open();
da.Fill(ds);
return "OK";
}
catch (Exception ex) { return ex.ToString(); }
}
}
CREATE PROCEDURE dbo.UpdateUserPassword
@UserName NVARCHAR(20),
@PassWord NVARCHAR(20)
AS
BEGIN
DECLARE @Err INT;
UPDATE WL_User SET Password = @PassWord WHERE UserName = @UserName;
SET @Err = @@ERROR; -- 0 成功,非 0 失敗
SELECT @Err AS ErrCode; -- 作為結果集返回
-- 亦可用 RETURN @Err 透過 ReturnValue 參數接收
END
public static string UpdatePassword(string user, string pwd)
{
using (SqlConnection conn = ADConnection.CreateConnection())
using (SqlCommand cmd = new SqlCommand("UpdateUserPassword", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@UserName", user);
cmd.Parameters.AddWithValue("@PassWord", pwd);
conn.Open();
int result = (int)cmd.ExecuteScalar(); // 獲取第一欄第一列
return (result == 0) ? "OK" : "FAILED";
}
}
ALTER PROCEDURE dbo.GetCustomerStats
@CustomerID INT
AS
BEGIN
IF @CustomerID = -1
BEGIN
-- 全部客戶統計
SELECT ContentOwnerID, UserCName, COUNT(*) AS TotalCount
FROM View_UserComment
GROUP BY ContentOwnerID, UserCName
ORDER BY ContentOwnerID DESC;
END
ELSE
BEGIN
-- 單一客戶統計
SELECT ContentOwnerID, UserCName, COUNT(*) AS TotalCount
FROM View_UserComment
WHERE ContentOwnerID = @CustomerID
GROUP BY ContentOwnerID, UserCName
ORDER BY ContentOwnerID DESC;
END
END
注意:T-SQL 使用 BEGIN...END 區塊而非大括號,條件判斷靈活支援複雜業務路由。
usp_<動詞>_<名詞>(如 usp_Get_UserList)TRY...CATCH(SQL 2005+)統一異常管理。