Monday, March 19, 2012

How to change a string

Hi,

I have a string like (Mike,David,John...). How can I change this string into a proper syntax of

('Mike','David','John'...) so that I can use it in an "IN" statement some where else.

Select * from TableName where Customer_Name In ('Mike','david','john',...)

Any function? Any Idea?

Thanks

An easier method might be to create a parameter called CustomerName and then use the following code:

Select * from TableName where Customer_Name IN(@.CustomerName)

|||

won't work, he needs to put the single quote on them...

Search for a user on this forum called Lisa Nicholls. she posted a solution for someone with a similiar issue, She even posted the code to use.

|||

With my example he would not have to worry about the quotes as the SQL operation addresses internally using the parameter. I have several of my reports built this way which allows me to avoid the quote issue.

|||

Thanks every one for the feed back. I have created the below function and it work fine.

CreateFUNCTION [dbo].[fn_StringWithQuotes] (@.InputString Varchar(8000))

RETURNSnvarchar(4000)

AS

BEGIN

DECLARE @.IDTable TABLE(Item Varchar(255))

DECLARE @.item VARCHAR(255)

WHILE(DATALENGTH(@.InputString)> 0)ANDRIGHT(SUBSTRING(@.InputString,1,CHARINDEX(',',@.InputString)),1)=','

BEGIN

SET @.item =SUBSTRING(@.InputString,1,(CHARINDEX(',', @.InputString)-1))

INSERTINTO @.IDTable(Item)VALUES(@.Item)

SET @.InputString =SUBSTRING(@.InputString,(CHARINDEX(',', @.InputString)+1),DATALENGTH(@.InputString))

END

INSERTINTO @.IDTable(Item)VALUES(@.InputString)

DECLARE @.NAME VARCHAR(255)

DECLARE @.NEW_NAME VARCHAR(255)

SET @.NEW_NAME=''

SELECT @.NEW_NAME = @.NEW_NAME +''','''+A.ITEM FROM(SELECT ITEM FROM @.IDTable)A

SET @.NEW_NAME=RIGHT(@.NEW_NAME,LEN(@.NEW_NAME)-2)+''''

RETURN @.NEW_NAME

END

No comments:

Post a Comment