Click here to Skip to main content
15,885,366 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have a table dbo.StockDetails

SQL
INT Varchar   INT
ID StockName SectorID

1 Abc 1
2 Win 1
3 CBH 2
4 Tes 3
5 Ras 5
6 GAS 3

Expected Result
ID
1
2
3
6

What I have tried:

SQL
Declare @SectorID varchar(50)='1,2'
select ID from dbo.StockDetails where SectorID IN (@SectorID)

Conversion failed when Converting the varchar value '1,2' to data type int.

My input parameter @SectorID data type is String with comma separator i mean its 1,2
Is there any possible way to fetch without creating a sql function?
Posted
Updated 16-Mar-22 4:16am
v3

If you use MS SQL Server, you can use STRING_SPLIT (Transact-SQL) - SQL Server | Microsoft Docs[^]

MSDN wrote:
As an example, the following SELECT statement uses the space character as the separator:

SQL
SELECT value FROM STRING_SPLIT('Lorem ipsum dolor sit amet.', ' ');


In a practice run, the preceding SELECT returned following result table:
value
------
Lorem
ipsum
dolor
sit
amet
.


Then you can join data, like this:
SQL
SELECT ID, StockName, SectorID  
FROM StockDetails
JOIN STRING_SPLIT(@SectorID,',')
    ON value = SectorID;  


As an alternative, you can use CTE[^] or custom function[^] to split string into parts.

Good luck
 
Share this answer
 
v3
You can achieve this through dynamic query like:
DECLARE @SectorID varchar(50) = '1,2'
DECLARE @Query VARCHAR(1000)
SET @Query = 'SELECT ID FROM [dbo].[StockDetails] WHERE SectorID IN (' + @SectorID + ')';
EXEC (@Query)
 
Share this answer
 
Comments
Richard Deeming 16-Mar-22 10:54am    
Which, unless you're extremely careful in constructing the parameter value, will leave you vulnerable to SQL Injection[^].

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900