Reputation: 163
This is the scenario:
My app will have the following:
How can I convert the string 1,2,3,4 into an integer type of data if my stored procedure is like this?
Select * from tblSomething Where ID in (1,2,3,4)
Upvotes: 0
Views: 10994
Reputation: 807
You can use the following SQL function.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[CommaSeparatedToString]
(
@psCSString VARCHAR(8000)
)
RETURNS @otTemp TABLE(sID VARCHAR(20))
AS
BEGIN
DECLARE @sTemp VARCHAR(50)
WHILE LEN(@psCSString) > 0
BEGIN
SET @sTemp = LEFT(@psCSString, ISNULL(NULLIF(CHARINDEX(',', @psCSString) - 1, -1),
LEN(@psCSString)))
SET @psCSString = SUBSTRING(@psCSString,ISNULL(NULLIF(CHARINDEX(',', @psCSString), 0),
LEN(@psCSString)) + 1, LEN(@psCSString))
INSERT INTO @otTemp VALUES (@sTemp)
END
RETURN
END
And call in your stored procedure like
Select * from tblSomething
Where ID in (SELECT * FROM CommaSeparatedToString('1,2,3,4'))
Upvotes: 1
Reputation: 1659
When you are storing a bunch of IDs into the array, store with single quote. so it will be ('1','2','3').
Then you no need to covert IDs into integer.
Upvotes: 0
Reputation: 1277
Use this function to split the value:
CREATE FUNCTION [dbo].[udfSplitCSV]
(
@String varchar (max),
@Delimiter varchar (10) = ','
)
RETURNS @ValueTable TABLE ([Row] int IDENTITY(1,1), [Value] varchar(max), [Length] int, [Duplicate] int NULL)
BEGIN
DECLARE @NextString varchar(max)
DECLARE @Pos int
DECLARE @NextPos int
IF @String IS NULL RETURN
--Initialize
SET @NextString = ''
SET @String = @String + @Delimiter
--Get position of first Comma
SET @Pos = charindex(@Delimiter,@String)
SET @NextPos = 1
--Loop while there is still a comma in the String
WHILE (@Pos <> 0)
BEGIN
SET @NextString = RTrim(LTrim(SubString(@String,1,@Pos - 1)))
INSERT INTO @ValueTable ([Value], [Length]) VALUES (@NextString, Len(@NextString))
SET @String = SubString(@String,@Pos+1,Len(@String))
SET @NextPos = @Pos
SET @Pos = CharIndex(@Delimiter,@String)
END
UPDATE @ValueTable
SET [Duplicate] = X.Duplicate
FROM @ValueTable VT
INNER JOIN (Select [Row], [Value], Row_Number() OVER (Partition By [Value] ORDER BY [Value], [Row]) as Duplicate FROM @ValueTable) X
ON X.[Row] = VT.[Row]
RETURN
END
-- Select * from dbo.udfSplitCSV('a , c b,c, a', ',')
Upvotes: 0
Reputation: 803
You need to create dynamic query for this
e.g you are getting list of values in @values paramter so prepare and run the dynamic query like this
DECLARE @query NVARCHAR(500)
DECLARE @values VARCHAR(200)
SET @values='1,2'
SET @query =N'Select * from tblSomething Where ID in ( ' + @values + ')'
SELECT @query
EXEC @Query
Upvotes: 0
Reputation: 1846
You can use the
SELECT CAST(MyVarcharCol AS INT) FROM Table
SELECT CONVERT(INT, MyVarcharCol) FROM Table
refer this link http://msdn.microsoft.com/en-us/library/ms187928.aspx
Upvotes: 0