繁体   English   中英

在我的C#中调用SQL函数

[英]Calling an SQL function in my C#

我在SSMS中创建了此功能。

这是为了创建用于为部门成员生成唯一ID的功能。 想法是将此函数返回的任何内容与数据库生成的另一个值连接起来。

CREATE FUNCTION [dbo].[ufnLeadingNumberOfZeroes](
    @Value INT, @NumberOfZeroes INT
) 
RETURNS varchar(MAX) 
WITH SCHEMABINDING 
AS 
BEGIN
    DECLARE @ReturnValue varchar(MAX);

    SET @ReturnValue = CONVERT(varchar(MAX), @Value);
    SET @ReturnValue = REPLICATE('0', @NumberOfZeroes - DATALENGTH(@ReturnValue)) + @ReturnValue;

    RETURN (@ReturnValue);
END

我希望在我的C#代码中调用它。 我已经有这个了:

private void memberID(object sender, EventArgs e)
{
    SqlConnection memberID = new SqlConnection(@"Data Source=EPRAISE-PC;Initial Catalog=master;Integrated Security=True");              
    using (SqlCommand comm = new SqlCommand("dbo.ufnLeadingNumberOfZeroes", memberID))
    {
        comm.CommandType = CommandType.StoredProcedure;

        SqlParameter p1 = new SqlParameter("@Value", SqlDbType.Int);
        // You can call the return value parameter anything, .e.g. "@Result".
        SqlParameter p2 = new SqlParameter("@NumberOfZeroes", SqlDbType.Int);

        p1.Direction = ParameterDirection.Input;
        p2.Direction = ParameterDirection.ReturnValue;

        p1.Value = deptCmbBox;

        comm.Parameters.Add(p1);
        comm.Parameters.Add(p2);

        memberID.Open();
        comm.ExecuteNonQuery();

    }
}

请问我的代码有什么问题?

尝试选择函数并改为使用ExecuteScalar。

private void memberID(object sender, EventArgs e)
{
    // create a connection
    using (SqlConnection conn = new SqlConnection(@"Data Source=EPRAISE-PC;Initial Catalog=master;Integrated Security=True"))          
    {
        // create a command
        SqlCommand cmd = new SqlCommand("SELECT dbo.ufnLeadingNumberOfZeroes(@Value, @NumberOfZeroes)", conn)

        // create parameters for the command
        SqlParameter value = new SqlParameter("@Value", SqlDbType.Int);
        SqlParameter numberOfZeroes = new SqlParameter("@NumberOfZeroes", SqlDbType.Int);

        // initialise the parameters' values
        value.Value = deptCmbBox;
        numberOfZeroes.Value = 0;

        // add the parameters to the command
        cmd.Parameters.Add(value);
        cmd.Parameters.Add(numberOfZeroes);

        // open the connection
        conn.Open();

        // execute the command and retrieve the result
        string str = cmd.ExecuteScalar();
    }
}

这里有几处错误。

一方面,您似乎正在尝试将输出参数与SQL UDF一起使用,这是不受支持的。 您只能将它们与存储过程一起使用。

另外,您的方法(似乎是事件处理程序)实际上并不会对其尝试检索的函数的结果执行任何操作。 您也没有给p2赋值,并且正如其他人指出的那样,您有错误的数据类型(应该int not bit )。 SQL UDF期望@NumberOfZeroes具有一个在计算中使用的值。 我不确定默认参数值是否不给定,但我假设它将为NULL ,并且在这种情况下,您的函数将返回NULL (我只是对其进行测试以确保)。

无论如何,这就是我对我认为您正在尝试做的事情的解释。 阅读评论,您需要考虑几件事。

注意,我将您尝试做的工作与事件处理程序方法分开了。

private void memberID(object sender, EventArgs e)
{
    int value = deptCmbBox; // if this is a combobox, you'll probably need to cast its SelectedText, SelectedValue or SelectedItem property to an integer
    int numZeroes = ??; // you'll have to give this a value or it'll return NULL

    string result = GetMemberID(value, numZeroes); // you'll have to decide how to store/use the resulting string here
}

private string GetMemberID(int value, int numberOfZeroes)
{
    SqlConnection conn = new SqlConnection(@"Data Source=EPRAISE-PC;Initial Catalog=master;Integrated Security=True");
    SqlCommand comm = new SqlCommand();
    SqlParameter param;
    string result;

    comm.CommandText = "SELECT dbo.ufnLeadingNumberOfZeroes(@Value, @NumberOfZeroes)";
    comm.CommandType = CommandType.Text;
    comm.Connection = conn;

    // Create and add the @Value parameter
    param = new SqlParameter();
    param.ParameterName = "@Value";
    param.Direction = ParameterDirection.Input;
    param.SqlDbType = SqlDbType.Int;
    param.Value = value;

    comm.Parameters.Add(param);

    // Create and add the @NumberOfZeros parameter
    param = new SqlParameter();
    param.ParameterName = "@NumberOfZeroes";
    param.Direction = ParameterDirection.Input;
    param.SqlDbType = SqlDbType.Int;
    param.Value = numberOfZeroes;

    comm.Parameters.Add(param);

    try
    {
        conn.Open();
        result = comm.ExecuteScalar().ToString();
        conn.Close();
    }

    catch (Exception ex)
    {
        throw ex;
    }

    finally // clean up after yourself
    {
        comm.Dispose();
        conn.Dispose(); // also closes the connection just in case it's left open
    }

    return result;
}

我很快就将其联系在一起,所以可能我遗漏了一些东西,但是它应该使您走上正确的道路。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM