简体   繁体   中英

Convert Comma Delimited String to bigint in SQL Server

I have a varchar string of delimited numbers separated by commas that I want to use in my SQL script but I need to compare with a bigint field in the database. Need to know to convert it:

DECLARE @RegionID varchar(200) = null
SET @RegionID = '853,834,16,467,841,460,495,44,859,457,437,836,864,434,86,838,458,472,832,433,142,154,159,839,831,469,442,275,840,299,446,220,300,225,227,447,301,450,230,837,441,835,302,477,855,411,395,279,303'

SELECT a.ClassAdID,    -- 1
        a.AdURL,        -- 2
        a.AdTitle,      -- 3
        a.ClassAdCatID, -- 4
        b.ClassAdCat,   -- 5
        a.Img1,         -- 6
        a.AdText,       -- 7
        a.MemberID,     -- 9
        a.Viewed,       -- 10
        c.Domain,       -- 11
        a.CreateDate    -- 12
        FROM ClassAd a  
        INNER JOIN ClassAdCat b ON b.ClassAdCAtID = a.ClassAdCAtID
        INNER JOIN Region c ON c.RegionID = a.RegionID
        AND a.PostType = 'CPN'
        AND DATEDIFF(d, GETDATE(), ExpirationDate) >= 0
        AND a.RegionID IN (@RegionID)
        AND Viewable = 'Y'

This fails with the following error:

Error converting data type varchar to bigint.

RegionID In the database is a bigint field.. need to convert the varchar to bigint.. any ideas..?

Many thanks in advance,

neojakey

create this function:

CREATE function [dbo].[f_split]
(
@param nvarchar(max), 
@delimiter char(1)
)
returns @t table (val nvarchar(max), seq int)
as
begin
set @param += @delimiter

;with a as
(
select cast(1 as bigint) f, charindex(@delimiter, @param) t, 1 seq
union all
select t + 1, charindex(@delimiter, @param, t + 1), seq + 1
from a
where charindex(@delimiter, @param, t + 1) > 0
)
insert @t
select substring(@param, f, t - f), seq from a
option (maxrecursion 0)
return
end

change this part:

AND a.RegionID IN (select val from dbo.f_split(@regionID, ','))

Change this for better overall performance:

AND DATEDIFF(d, 0, GETDATE()) <= ExpirationDate

Your query does not know that those are separate values, you can use dynamic sql for this:

DECLARE @RegionID varchar(200) = null
SET @RegionID = '853,834,16,467,841,460,495,44,859,457,437,836,864,434,86,838,458,472,832,433,142,154,159,839,831,469,442,275,840,299,446,220,300,225,227,447,301,450,230,837,441,835,302,477,855,411,395,279,303'

declare @sql nvarchar(Max)

set @sql = 'SELECT a.ClassAdID,    -- 1
        a.AdURL,        -- 2
        a.AdTitle,      -- 3
        a.ClassAdCatID, -- 4
        b.ClassAdCat,   -- 5
        a.Img1,         -- 6
        a.AdText,       -- 7
        a.MemberID,     -- 9
        a.Viewed,       -- 10
        c.Domain,       -- 11
        a.CreateDate    -- 12
        FROM ClassAd a  
        INNER JOIN ClassAdCat b ON b.ClassAdCAtID = a.ClassAdCAtID
        INNER JOIN Region c ON c.RegionID = a.RegionID
        AND a.PostType = ''CPN''
        AND DATEDIFF(d, GETDATE(), ExpirationDate) >= 0
        AND a.RegionID IN ('+@RegionID+')
        AND Viewable = ''Y'''

exec sp_executesql @sql

I use this apporach sometimes and find it very good. It transfors your comma-separated string into an AUX table (called #ARRAY) and then query the main table based on the AUX table:

declare @RegionID varchar(50)
SET @RegionID = '853,834,16,467,841,460,495,44,859,457,437,836,864,434,86,838,458,472,832,433,142,154,159,839,831,469,442,275,840,299,446,220,300,225,227,447,301,450,230,837,441,835,302,477,855,411,395,279,303'
declare @S varchar(20)
if LEN(@RegionID) > 0 SET @RegionID = @RegionID + ',' 
CREATE TABLE #ARRAY(region_ID VARCHAR(20))

WHILE LEN(@RegionID) > 0 BEGIN
   SELECT @S = LTRIM(SUBSTRING(@RegionID, 1, CHARINDEX(',', @RegionID) - 1))
   INSERT INTO #ARRAY (region_ID) VALUES (@S)
   SELECT @RegionID = SUBSTRING(@RegionID, CHARINDEX(',', @RegionID) + 1, LEN(@RegionID))
END

select * from your_table
where regionID IN (select region_ID from #ARRAY)

It avoids you from ahving to concatenate the query string and then use EXEC to execute it, which I dont think it is a very good approach.

if you need to run the code twice you will need to drop the temp table

I think the answer should be kept simple.
Try using CHARINDEX like this:

DECLARE @RegionID VARCHAR(200) = NULL 

SET @RegionID = 
'853,834,16,467,841,460,495,44,859,457,437,836,864,434,86,838,458,472,832,433,142,154,159,839,831,469,442,275,840,299,446,220,300,225,227,447,301,450,230,837,441,835,302,477,855,411,395,279,303'

SELECT 1 
WHERE  Charindex('834', @RegionID) > 0 

SELECT 1 
WHERE  Charindex('999', @RegionID) > 0 

When CHARINDEX finds the value in the large string variable, it will return it's position, otherwise it return 0.
Use this as a search tool.

The easiest way to change this query is to replace the IN function with a string function. Here is what I consider the safest approach using LIKE (which is portable among databases):

    AND ','+@RegionID+',' like '%,'+cast(a.RegionID as varchar(255))+',%'

Or CHARINDEX :

    AND charindex(','+cast(a.RegionID as varchar(255))+',', ','+@RegionID+',') > 0

However, if you are explicitly putting the list in your code, why not use a temporary table?

declare @RegionIds table (RegionId int);
insert into @RegionIds
    select 853 union all
    select 834 union all
    . . .
    select 303

Then you can use the table in the IN clause:

   AND a.RegionId in (select RegionId from @RegionIds)

or in a JOIN clause.

I like Diego's answer some, but I think my modification is a little better because you are declaring a table variable and not creating an actual table. I know the "in" statement can be a little slow, so I did an inner join since I needed some info from the Company table anyway.

declare @companyIdList varchar(1000)
set @companyIdList = '1,2,3'

if LEN(@companyIdList) > 0 SET @companyIdList = @companyIdList + ',' 
declare @CompanyIds TABLE (CompanyId bigint)
declare @S varchar(20)
WHILE LEN(@companyIdList) > 0 BEGIN
   SELECT @S = LTRIM(SUBSTRING(@companyIdList, 1, CHARINDEX(',', @companyIdList) - 1))
   INSERT INTO @CompanyIds (CompanyId) VALUES (@S)
   SELECT @companyIdList = SUBSTRING(@companyIdList, CHARINDEX(',', @companyIdList) + 1, LEN(@companyIdList))
END

select d.Id, d.Name, c.Id, c.Name 
from [Division] d 
    inner join [Company] c on d.CompanyId = c.Id
    inner join @CompanyIds cids on c.Id = cids.CompanyId

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