简体   繁体   English

无效的强制转换例外?

[英]Invalid cast exception?

I have the following stored procedure: 我有以下存储过程:

Create PROCEDURE [dbo].[GETVendorsStatsAgainstSearTerm]
    @Date DateTime , 
    @SearchId  bigint
AS

declare @cmd as varchar(2000)
set @cmd = ' select *, ' + cast(SearchId as varchar) + ' as SearhId   from tbl'
exec (@cmd)

I want to treat SearchId as a column to run the select query against. 我想将SearchId视作一列针对其运行选择查询。 I want to know the correct type for the SearchId column. 我想知道SearchId列的正确类型。

I am unable to convert this SearchId column into a long data type in C#. 我无法将此SearchId列转换为C#中的长数据类型。 Can anybody help me? 有谁能够帮助我?

您可以尝试使用Convert function

Convert(varchar(50),SearchId ) 

I guess the problem is that there are some unassigned SearchId's which causes csating a null into varchar. 我猜问题是有一些未分配的SearchId导致将空值引用到varchar中。

Try something like this: 尝试这样的事情:

//...
set @cmd = CASE
   WHEN (SearchId IS NOT NULL) THEN (' select *, ' + cast(SearchId as varchar) + ' as SearhId from tbl')
   ELSE ' select *, 0 as SearhId from tbl'
END
///... 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM