在 ASP.NET 中调用 UDF
Posted
技术标签:
【中文标题】在 ASP.NET 中调用 UDF【英文标题】:Calling UDF in ASP.NET 【发布时间】:2015-09-08 00:33:09 【问题描述】:我是 ASP.NET 的新手,在如何在我的 ASP.NET Web 应用程序中调用内联用户定义函数时遇到了麻烦。
在这里,我在函数中传递了两个参数 - 一个是可用的 leave(lv),另一个是持续时间 (dr)。我只是从 lv 中减去 dr 并返回值。但是我在调用该函数时遇到问题。
我尝试过“SELECT dbo.emp_leave_sub(lv,dr) as remaining”而不是查询“SELECT dbo.emp_leave_sub(lv,dr) FROM Employee1 where Employee1.emp_id='”+emp_id +“'”但是它没用。我不明白我做错了什么。
期待您的友好回复。任何帮助将不胜感激。
下面是我的功能:
ALTER FUNCTION dbo.emp_leave_sub(@available int, @duration int)
RETURNS int
AS
-- Returns the availabe leave after deduction for the employee.
BEGIN
DECLARE @ret int;
SELECT @ret = @available - @duration;
RETURN @ret;
END;
And this is from where I am calling my function :
try
SqlDataReader rdr;
SqlConnection conn = new SqlConnection (ConfigurationManager.
ConnectionStrings["PMSConnectionString"].ConnectionString);
conn.Open();
string sub_leave = "SELECT dbo.emp_leave_sub(lv,dr) FROM ` ` Employee1 where Employee1.emp_id='" + emp_id + "'";
SqlCommand com2 = new SqlCommand(sub_leave, conn);
com2.CommandType = CommandType.Text;
using (conn)
//read data from the table to our data reader
rdr = com2.ExecuteReader();
//loop through each row we have read
while (rdr.Read())
remaining = rdr.GetInt32(0);
rdr.Close();
【问题讨论】:
Employee1 表上是否声明了 'lv' 和 'dr' 列?另外,请不要将 emp_id 变量直接注入到您的 SQL 语句中,请使用参数,如 @thewisegod 的答案中的(现在)。 那么你找到答案了吗? @Will Hughes - 嗨,不,它们不是我的 Employee1 表的列。它们是我保存从 Employee1 获得的两个值的变量。 【参考方案1】:尝试这样做:
SqlDataReader rdr;
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["PMSConnectionString"].ConnectionString))
conn.Open();
string sub_leave = "SELECT dbo.emp_leave_sub(@available,@duration) FROM Employee1 where Employee1.emp_id=@empid";
SqlCommand com2 = new SqlCommand(sub_leave, conn);
com2.Parameters.AddWithValue("@available", your value);
com2.Parameters.AddWithValue("@duration", your value);
com2.Parameters.AddWithValue("@empid", emp_id);
com2.CommandType = CommandType.Text;
//read data from the table to our data reader
rdr = com2.ExecuteReader();
//loop through each row we have read
while (rdr.Read())
remaining = rdr.GetInt32(0);
rdr.Close();
【讨论】:
更新了答案:如果要声明变量,则需要在语句中使用它们。此外,emp_id 应该是一个参数,而不是像那样注入到 SQL 语句中(是的,我知道它在原始问题中,但没有理由不更新语句来修复它)。 嗨,,,这行得通... :) :) 虽然我不得不将“@available”和“@duration”更改为 Employee1 表的列名。否则 UDF 返回 0。无论如何,非常感谢... :) :)以上是关于在 ASP.NET 中调用 UDF的主要内容,如果未能解决你的问题,请参考以下文章
使用 .NET 6 在 ASP.NET Core 中处理 API 调用中的空子类