我有这个程序:
ALTER procedure dbo.scUsuarioCorrecto
@usrLogin nvarchar(15),
@usrPassword nvarchar(255)
AS
select case when exists
(select * from Usuario where usrLogin =
@usrLogin and usrPassword = @usrPassword
AND usrHabilitado = 1)
then CAST(1 as bit) else CAST(0 as bit) end as correcto;
我无法改变它,所以我必须解决它,我如何从C#中捕获该位,我已经连接到数据库并且我能够调用某些程序,但我遇到了这个问题
尝试将参数设置为输出:
SqlParameter result = new SqlParameter("correcto", SqlDbType.Int)
{
Direction = ParameterDirection.Output
};
cmd.Parameters.Add(result);
但我得到了许多参数""错误,抱歉,如果我犯了一个愚蠢的错误,我今天开始使用C#,我也使用了搜索按钮。
答案 0 :(得分:3)
问题是,您正在执行存储过程并尝试读取它,就像有Output parameter一样。如果您无法修改存储过程以提供输出参数,请将代码修改为以下内容:
using (var connection = new SqlConnection())
{
connection.ConnectionString = "Your Connection String";
using (var command = new SqlCommand())
{
command.Connection = connection;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "scUsuarioCorrecto";
command.Parameters.AddWithValue("@usrLogin", "Your login");
command.Parameters.AddWithValue("@usrPassword", "Your password");
connection.Open();
using (var adapter = new SqlDataAdapter())
{
using (var ds = new DataSet())
{
adapter.SelectCommand = command;
adapter.Fill(ds);
if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
{
var correcto = (bool)ds.Tables[0].Rows[0]["correcto"];
} else
{
// Something went wrong
}
}
}
}
}
答案 1 :(得分:1)
我想把它放在我对Icemanind的帖子的评论中(但是为了便于阅读而单独发布)。此版本使用ExecuteScalar:
using (var connection = new SqlConnection())
{
connection.ConnectionString = "Your Connection String";
using (var command = new SqlCommand())
{
command.Connection = connection;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "scUsuarioCorrecto";
command.Parameters.AddWithValue("@usrLogin", "Your login");
command.Parameters.AddWithValue("@usrPassword", "Your password");
connection.Open();
object obj = command.ExecuteScalar();
if (obj is bool)
{
bool correcto = (bool)obj;
}
else
{
// either empty result set, or value in row is NULL.
}
}
}
关于ExecuteScalar的一般说明:
如果SQL请求导致空结果集,则obj将为null(即C#为null)。如果结果集至少有一行,但第一列的值为NULL(即SQL Server为NULL),则obj将为DBNull.Value。
答案 2 :(得分:0)
该过程仅采用两个参数。在这种情况下,由于它正在进行选择,您应该能够从标准SELECT
语句中读取它。
答案 3 :(得分:-1)
问题是您需要使用OUTPUT
设置参数USE AdventureWorks2008R2;
GO
IF OBJECT_ID('Sales.uspGetEmployeeSalesYTD', 'P') IS NOT NULL
DROP PROCEDURE Sales.uspGetEmployeeSalesYTD;
GO
CREATE PROCEDURE Sales.uspGetEmployeeSalesYTD
@SalesPerson nvarchar(50),
@SalesYTD money OUTPUT
AS
SET NOCOUNT ON;
SELECT @SalesYTD = SalesYTD
FROM Sales.SalesPerson AS sp
JOIN HumanResources.vEmployee AS e ON e.BusinessEntityID = sp.BusinessEntityID
WHERE LastName = @SalesPerson;
RETURN
GO