Click here to Skip to main content
15,885,141 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have table state master and citymaster
in statemaster table contain

stateid and state name

and citymaster table contain

cityid stateid cityname


i want to get result from citymaster
and i am passing stateid in where condition like '1,2'



--[dbo].[SP_GET_CITY_BY_STATE] '1,2'
-- =============================================
ALTER PROCEDURE [dbo].[SP_GET_CITY_BY_STATE]
@STATE_ID1 varchar =null
AS
BEGIN
SELECT TBL_CITY.CITY_NAME,TBL_CITY.CITY_ID FROM TBL_CITY WHERE TBL_CITY.STATE_ID IN(@STATE_ID1)

END
Posted
Updated 13-Jan-15 22:33pm
v2
Comments
Member 11049825 14-Jan-15 5:00am    
thank you very much sir
Member 11049825 14-Jan-15 5:00am    
now its working fine

Unfortunately, it doesn't work like that: IN expressions are "precompileed", so you will get an error.
There is a way to do it: Using comma separated value parameter strings in SQL IN clauses[^]
 
Share this answer
 
We cannot pass parameter value as string for integer column.

Please try this.

Solution:

Step 1: Create a function

CREATE function [dbo].[fn_StringToParameter]
(
@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

Step 2: Modify your stored Procedure

SQL
--[dbo].[SP_GET_CITY_BY_STATE] '1,2'
    -- =============================================
    ALTER PROCEDURE [dbo].[SP_GET_CITY_BY_STATE]
    @STATE_ID1 varchar =null
    AS
    BEGIN
    SELECT TBL_CITY.CITY_NAME,TBL_CITY.CITY_ID FROM TBL_CITY WHERE TBL_CITY.STATE_ID
    IN(SELECT val FROM dbo.fn_StringToParameter(@STATE_ID1, ','))
    
    END
 
Share this answer
 
Try the exec keyword to execute a script.

SQL
declare @cStatement varchar(max)
set @cStatement = 'SELECT TBL_CITY.CITY_NAME,TBL_CITY.CITY_ID FROM TBL_CITY WHERE TBL_CITY.STATE_ID IN(' + @STATE_ID1 + ')'

exec(@cStatement)
 
Share this answer
 

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