简体   繁体   中英

What is wrong with my SQL function that it always returns null when I try to retrieve its value in C#?

What is wrong with my SQL function that it always returns null when I try to retrieve its value in C#? The function works pretty solid in the SQL designer but when I try to run it using C# it fails.

This is my function definition. First the Table Valued Function:

ALTER FUNCTION dbo.FGetNumberOfChikensInThisDate
    (
    @Date nvarchar(12),
    @IDSource bigint
    )
RETURNS Table 
AS
    RETURN SELECT     SUM(NumberOfChicken) AS Number of Chickens  
       FROM            tblChickens
           WHERE        (SourceID= @IDSource) AND (ReservedDate = @Date)

And this is the Scalar Valued Function :

ALTER FUNCTION dbo.FSGetNumberOfChikensInThisDate
    (
    @Date nvarchar(12),
    @IDSource bigint
    )
RETURNS bigint
AS
 BEGIN
  DECLARE  @ret bigint;
   SELECT      @ret=  SUM(NumberOfChicken) 
       FROM            tblChickens
          WHERE        (ReserveDate = @Date) AND (SourceID= @IDSource)
RETURN @ret;
END;

I use these two methods to create the SQL command string for these functions and pass their parameters and execute them from C#: For table based functions I use:

public static DataTable ExecuteSqlFunction(string functionName, string[] Functionparamers)
        {
            SqlDataAdapter reader = new SqlDataAdapter();
            DataTable table = new DataTable();
            string query = "select * from " + functionName + "(";
            int index = 0;
            foreach (string item in Functionparamers)//{0},{0}
            {
                query += String.Format("{0}", item);
                query += ++index >= Functionparamers.Length ? String.Format(")", item) : ",";
            }

            if (connection.State != ConnectionState.Open)
            { connection.Open(); }

            cmd = new SqlCommand(query, connection);
            reader.SelectCommand = cmd;
            reader.Fill(table);
            connection.Close();
            return table;

        }

and using it like this :

ExecuteSqlFunction("dbo.FGetNumberOfChikensInThisDate",new string[] { Date, API.CurrentSourceID });

will create this string :

select * from dbo.FGetNumberOfChikensInThisDate(1391/12/01,4) //the date is in Persian

The returning DataTable object has one row but when I write

dataTable.Rows[0][0].ToString();

I get a

""

string while when I run this SQL command on the SQL it runs just fine! (Actually I try to execute the SQL command of this function inside SQL designer and i get the results just fine but when i try to run it using c# it just acts like this).

And for the scalar valued function is use the same former method with a slight change at the end:

 public static object ExecuteScalarSqlFunction(string functionName, string[] FunctionParameters)
        {

            string query = "select * from " + functionName + "(";
            int index = 0;
            object result;
            foreach (string item in FunctionParameters)//{0},{0}
            {
                query += String.Format("{0}", item);
                query += ++index >= FunctionParameters.Length ? String.Format(")", item) : ",";
            }

            if (connection.State != ConnectionState.Open)
            { connection.Open(); }

            cmd = new SqlCommand(query, connection);
            result = cmd.ExecuteScalar();
            connection.Close();
            return result;
        }

Calling this function like this:

ExecuteScalarSqlFunction("dbo.FSGetNumberOfChikensInThisDate",new string[] { Date, API.CurrentSourceID });

Will create this SQL string:

"select * from dbo.FSGetNumberOfChikensInThisDate(1391/12/01,4)"

and when I get to the

result = cmd.ExecuteScalar(); 

section it generates an exception saying:

Invalid object name 'dbo.FSGetNumberOfChikensInThisDate'. while it does exists ! and is there!.

The ExecuteSqlFunction() is working for the rest of my functions but these are exceptions which fail. The ExecuteScalarFunction is not tested since I don't know if I have missed anything in it but I'm sure the ExecuteSqlFunction which deals with table valued SQL functions is OK so it must be something else that I am missing here.

The function FSGetNumberOfChikensInThisDate returns a scalar value - a single result of type bigint - which cannot be used as the source of a SELECT statement. It can be used as a column source for a SELECT statement however.

Try this SQL statement instead:

SELECT dbo.FSGetNumberOfChikensInThisDate('1391/12/01', 4);

Should return a single row with a single unnamed BigInt column result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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