Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast ExecuteScalar result to a GUID with out using a string?

How can I cast the result of an ExecuteScalar command to a GUID structure without first using .ToString() to pass to the constructor of the GUID?

The reason for doing this is performance and not creating thousands of unnecessary string objects in memory.

It is possible using a reader and the GetGUID Method but I can not see any references to how to achieve the same when using a scalar value.

Update: I also need to handle DBNull Values

like image 275
John Avatar asked Jan 10 '11 16:01

John


People also ask

What does ExecuteScalar return if no rows?

If the row does not exist, the result of command. ExecuteScalar() is null, which is then casted to a null string and assigned to getusername .

What does ExecuteScalar return?

ExecuteScalar Method. Executes the query, and returns the first column of the first row in the result set returned by the query. Extra columns or rows are ignored.

What is use of ExecuteScalar() method?

Use the ExecuteScalar method to retrieve a single value (for example, an aggregate value) from a database. This requires less code than using the ExecuteReader method, and then performing the operations that you need to generate the single value using the data returned by a SqlDataReader.

When to use ExecuteScalar in c#?

ExecuteScalar is typically used when your query returns a single value. If it returns more, then the result is the first column of the first row. An example might be SELECT @@IDENTITY AS 'Identity' . ExecuteReader is used for any result set with multiple rows/columns (e.g., SELECT col1, col2 from sometable ).


1 Answers

Assuming that your sql statement cannot return DBNull.Value, then yes you can:

Guid myResult = (Guid) cmd.ExecuteScalar();

EDIT: Now that we know you need to handle nulls.... :-)

I can think of two ways to handle nulls - use a nullable Guid and set it to null, or use a regular Guid and have it set to Guid.Empty if your SQL statement returns null.

Consider some form of helper function or extension method which checks for DBNull.Value.

    static Guid? GetGuidFromDb(object dbValue)
    {
        if (dbValue == null || DBNull.Value.Equals(dbValue))
        {
            return null;
        }
        else
        {
            return (Guid) dbValue;
        }
    }

or

    static Guid GetGuidFromDb(object dbValue)
    {
        if (dbValue == null || DBNull.Value.Equals(dbValue))
        {
            return Guid.Empty;
        }
        else
        {
            return (Guid) dbValue;
        }

Then call

Guid? myResult = GetGuidFromDb(cmd.ExecuteScalar());

Note - this will choke if your SQL command returns a datatype other than UniqueIdentifier.

like image 89
Neil Moss Avatar answered Sep 30 '22 06:09

Neil Moss