gpt4 book ai didi

c# - 通过存储过程传递参数

转载 作者:行者123 更新时间:2023-11-30 22:41:55 27 4
gpt4 key购买 nike

我不熟悉将 DB 与应用程序连接,我正在尝试从数据库中提取几个字段,我指定的参数应该过滤掉结果。我一直收到没有提供参数或参数。任何人都可以对此有所了解吗?谢谢。

下面是存储过程:

ALTER PROC dbo.PassParamUserID

AS
set nocount on
DECLARE @UserID int;

SELECT f_Name, l_Name
FROM tb_User
WHERE tb_User.ID = @UserID;

这是我的代码

class StoredProcedureDemo
{
static void Main()
{
StoredProcedureDemo spd = new StoredProcedureDemo();

//run a simple stored procedure that takes a parameter
spd.RunStoredProcParams();
}

public void RunStoredProcParams()
{
SqlConnection conn = null;
SqlDataReader rdr = null;

string ID = "2";

Console.WriteLine("\n the customer full name is:");

try
{
//create a new connection object
conn = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=c:\\Program Files\\Microsoft SQL Server\\MSSQL10.SQLEXPRESS\\MSSQL\\DATA\\UserDB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True; Integrated Security=SSPI");
conn.Open();

//create command objects identifying the stored procedure
SqlCommand cmd = new SqlCommand("PassParamUserID", conn);

//Set the command object so it know to execute the stored procedure
cmd.CommandType = CommandType.StoredProcedure;

//ADD PARAMETERS TO COMMAND WHICH WILL BE PASSED TO STORED PROCEDURE
cmd.Parameters.Add(new SqlParameter("@UserID", 2));

//execute the command
rdr = cmd.ExecuteReader();

//iterate through results, printing each to console
while (rdr.Read())
{
Console.WriteLine("First Name: {0,25} Last Name: {0,20}", rdr["f_Name"], rdr["l_Name"]);
}
}

最佳答案

您需要将 SQL 存储过程修改为:

ALTER PROC dbo.PassParamUserID

@UserID int

AS set nocount on

SELECT f_Name, l_Name FROM tb_User WHERE tb_User.ID = @UserID;

目前您只是在过程中将其声明为变量。

以下是一些 MSDN 文章,可以帮助您继续前进:

Creating and Altering Stored procedures

Declaring Local Variables

关于c# - 通过存储过程传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4661058/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com