当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - Getting DateTime from stored procedure error

问题描述:

I am trying to pull a DateTime from a stored procedure on my SQL Server.

Stored procedure variable:

@TempDateTime DateTime = '' OUTPUT

SET @TempDateTime = GETDATE()

Line that errors out in my C# CF 2.0 Program

DateTime tempDT = Convert.ToDateTime(sqlcmd.Parameters["@TempDateTime"].Value);

I get the following error, and I am at a lost on what it is. Can my stored procedure be sending back a null? I execute the stored procedure and it runs fine, on another bit of code. Getting the DateTime and inserting it into a table, but errors when I try to retrieve the DateTime var.

System.IndexOutOfRangeException was unhandled

Message="An {0} with {1} '{2}' is not contained by this {3}."

StackTrace:

at System.Data.SqlClient.SqlParameterCollection.RangeCheck()

at System.Data.SqlClient.SqlParameterCollection.get_Item()

at Missouri_Scanning_Utility.Form1.updateDatabase()

at Missouri_Scanning_Utility.Form1.tmrUpdateDatabase_Tick()

at System.Windows.Forms.Timer._WnProc()

at System.Windows.Forms.ApplicationThreadContext._InternalContextMessages()

at Microsoft.AGL.Forms.EVL.EnterMainLoop()

at System.Windows.Forms.Application.Run()

at Missouri_Scanning_Utility.Program.Main()

网友答案:

When you are defining the parameter values to your send to your call, you have to declare the OUTPUT parameters accordingly.

Since you do not have the relevant portions of your code posted, here is the general procedure for doing this:

var tempDateTimeParam = new SqlParameter("@TempDateTime", SqlDbType.DateTime)
{ 
    Direction = ParameterDirection.Output 
};

myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.Add(tempDateTimeParam);
// Add additional params.

// Execute stored proc.

// Read result from output param which should now have a value.
var tempDateTimeValue = (DateTime)tempDateTimeParam.Value;
分享给朋友:
您可能感兴趣的文章:
随机阅读: