Int64在存储过程调用中强制转换为Byte []

时间:2010-11-03 04:34:04

标签: c# sql-server stored-procedures casting

我有一个看起来像这样的存储过程:

create procedure [dbo].[Batch_of_Things_Get] (@MaxTimestamp binary(8)) as 
begin
    set nocount on

    select top 3500
        i.ThingID,
        i.Name,
        i.CreationDate,
        i.local_timestamp
    from
        [dbo].[Thing] i
    where
        i.local_timestamp > @MaxTimestamp
end

和一些C#代码(在.NET 3.5中)通过System.Data.SqlClient调用它,使用long @MaxTimestamp参数。

    public static string GetUpdatedThings(long MinTimestamp)
    {
        // the ExecuteXmlDocument call takes: string SPName, params object[] SPParams
        return new SqlProcedure(Config.ConnectionString).ExecuteXmlDocument("Batch_of_Things_Get", MinTimestamp).OuterXml;
    }

它曾经工作过(实际上在制作中确实仍然非常愉快),但是我的开发副本现在正在抛出:

InvalidCastException:无法将参数值从Int64转换为Byte []。

堆栈跟踪:

at System.Data.SqlClient.SqlParameter.CoerceValue(Object value, MetaType destinationType)
at System.Data.SqlClient.SqlParameter.GetCoercedValue()
at System.Data.SqlClient.SqlParameter.Validate(Int32 index, Boolean isCommandProc)
at System.Data.SqlClient.SqlCommand.SetUpRPCParameters(_SqlRPC rpc, Int32 startCount, Boolean inSchema, SqlParameterCollection parameters)
at System.Data.SqlClient.SqlCommand.BuildRPC(Boolean inSchema, SqlParameterCollection  parameters, _SqlRPC& rpc)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
at System.Data.SqlClient.SqlCommand.ExecuteXmlReader()

现在我可以理解为什么现在失败了,但为什么不提前呢?

编辑:我更改了C#代码以将long转换为Byte [],现在它正在抛出:Failed to convert parameter value from a Byte[] to a Int64.,这与最初抱怨的相反!

1 个答案:

答案 0 :(得分:0)

BitConverter.GetBytes是一个方便的实用功能