简体   繁体   中英

Datetime returning null in a stored procedure

I am executing a stored procedure inside another stored procedure.

I pass the parameters and when the value is not null, it works perfectly fine, but when the value generates as 0 rows, it gives me error.

Stored procedure:

    declare @LDate datetime
    declare @DateEntered datetime

    insert into Table1 values(5,5)

    EXEC @LDate = GetLDate @ID, @GID   // other stored procedure inside the main stored procedure
    // GetLDate is ("select Date1 from TableGetDate where @ID =4,@GID=5")

    if(CAST(@LDate as datetime) < CAST(@DateEntered as datetime))
        Select '-1'
    else
        SELECT '-2'

When in the C# code I call ExecuteScalar , it returns null if @LDate returns no date. If @LDate returns a date then everything works perfectly fine.

How to solve this?

You could safely convert the return object to a datetime if the object value is null.

DateTime dateTime = new DateTime();
try
{
 dateTime = Convert.ToDateTime(cmd.ExecuteScalar());
}
catch
{
 dateTime = new DateTime(1900, 1, 1);
}

You don't need to cast a datetime as a datetime. That doesn't do anything.

declare @LDate datetime
declare @DateEntered datetime

EXEC @LDate = GetLDate @ID,@GID //Other store proc inside the main store proc

if (@LDate is null)
   SELECT '0' 
else if( @LDate < @DateEntered )
    SELECT '-1'
else
    SELECT '-2'

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