Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explain me this SELECT dbo.TableName(@variable) statement

I'm working on one program that I need to modify a little. There's one SQL statement I don't understand what it does (or basically how it does it).

string query = "SELECT dbo.BusinessMinutes(@start,@end,@priorityid)";

SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.Add("@start", SqlDbType.DateTime).Value = start;
cmd.Parameters.Add("@end", SqlDbType.DateTime).Value = end;
cmd.Parameters.Add("@priorityid", SqlDbType.UniqueIdentifier).Value = priorityId;                    

SqlDataAdapter READER = new SqlDataAdapter();
READER.SelectCommand = cmd;                    

DataTable table = new DataTable();
READER.Fill(table);

if (table.Rows.Count == 1)
{                                             
    minutes = (int)table.Rows[0][0];
}

So can someone explain me the SELECT statement there. The end result (minutes) is as expected so it works but that syntax confuses me. Is this somehow equal to SELECT * FROM dbo.BusinessMinutes WHERE...

Is this commonly used and does this syntax has some special name so I could name my question better? Thank you in advance.

like image 974
kivikall Avatar asked Jul 29 '26 05:07

kivikall


2 Answers

dbo.BusinessMinutes has to be a UDF (User Defined Function) that returns a simple scalar value based on a starting date, an ending date and a priority indicator.

Scalar functions, be it UDF or native, can be used in a SELECT statement to produce a field in the returned resultset. Thus, the code you have is perfectly legal.

For more information about scalar UDF, read this MSDN article.

As a side note, a better implementation for that code would be this:

string query = "SELECT dbo.BusinessMinutes(@start,@end,@priorityid)";

using (SqlCommand cmd = new SqlCommand(query, con))
{
    cmd.Parameters.Add("@start", SqlDbType.DateTime).Value = start;
    cmd.Parameters.Add("@end", SqlDbType.DateTime).Value = end;
    cmd.Parameters.Add("@priorityid", SqlDbType.UniqueIdentifier).Value = priorityId;                    

    // assuming connection is already open
    using (SqlDataReader reader = cmd.ExecuteReader())
    {
        if (reader.Read()) minutes = reader.GetInt32(0);
    }
}

If all you want is to init the minutes variable, using SqlDataReader will be more efficient and performant than creating a SqlDataAdapter and a DataTable. The using statements will also make sure your SqlCommand and SqlDataReader objects gets disposed of properly.

like image 169
Crono Avatar answered Jul 30 '26 17:07

Crono


It is not a table name. I think you call into a FUNCTION.

how to create and call scalar function in sql server 2008

has more explanations and examples.

like image 39
TomTom Avatar answered Jul 30 '26 17:07

TomTom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!