简体   繁体   中英

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. I want to know the correct type for the SearchId column.

I am unable to convert this SearchId column into a long data type in 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.

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
///... 

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