Casting BIGINT as Varchar Err

Neil 396 Reputation points
2020-10-15T19:17:19.92+00:00

I have a SP like below for the, if I want to pass multiple ids like 1111, 2222 I am getting error even If I cast ID as varchar(100)

BEGIN
Declare @ID BIGINT
SELECT @ID = 1111

SELECT * INTO TAB1 FROM TAB2 WHERE ID IN @ID 
..
..
SELECT * INTO TABn FROM TABm WHERE ID IN @ID 
END

I tried below it didn't worked. with the above code I am forced to use only one value e.g. 1111

BEGIN
Declare @ID VARCHAR(100)
SELECT @ID = ('1111','2222')

SELECT * INTO TAB1 FROM TAB2 WHERE CAST(ID as VARCHAR(100)) IN @ID 
..
..
SELECT * INTO TABn FROM TABm WHERE CAST(ID as VARCHAR(100)) IN @ID 
END
SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
14,490 questions
Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,690 questions
0 comments No comments
{count} votes

Accepted answer
  1. Guoxiong 8,206 Reputation points
    2020-10-15T19:36:39+00:00

    SELECT @ID = ('1111','2222') is not correct. Try the following script if your SQL server is 2016, 2017 or 2019:

    DECLARE @ID VARCHAR(100)
    SET @ID = '1111,2222';
    SELECT value FROM STRING_SPLIT(@ID, ',');
    

    For you case:

    SELECT * INTO TAB1 FROM TAB2 WHERE ID IN (SELECT value FROM STRING_SPLIT(@ID, ','))
    
    1 person found this answer helpful.
    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Tom Phillips 17,746 Reputation points
    2020-10-15T20:12:51.627+00:00
    1 person found this answer helpful.
    0 comments No comments

  2. Neil 396 Reputation points
    2020-10-15T20:33:59.86+00:00

    Thanks GuoxiongYuan I tested this, it worked.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.