Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

putting apostrophe in string from a function? 1

Status
Not open for further replies.

x6213

Programmer
Aug 17, 2005
17
US
I have a procedure that starts something like this
function exampleX(@value1,@value2,@string1)

that is built from an online form with 3 variables and one of the variables is a string
and when I greate the sql string i get something like

exec exampleX(value1,value2,'string1,string2,string3')

how do I convert the string 'string1,string2,string3' to
'string1','string2','string3' so i can use is in a

select * from table1 where stringtype is not in (@string1)
 
First, create a user defined function

Code:
Create Function Split(@CommaDelimitedFieldNames Varchar(8000),@SplitChar VarChar(10))  
Returns @Tbl_FieldNames Table  (FieldName VarChar(8000))  As  

Begin 
 Set @CommaDelimitedFieldNames =  @CommaDelimitedFieldNames + @SplitChar

 Declare @Pos1 Int
 Declare @pos2 Int
 
 Set @Pos1=1
 Set @Pos2=1

 While @Pos1<Len(@CommaDelimitedFieldNames)
 Begin
  Set @Pos1 = CharIndex(@SplitChar,@CommaDelimitedFieldNames,@Pos1)
  Insert @Tbl_FieldNames Select  Cast(Substring(@CommaDelimitedFieldNames,@Pos2,@Pos1-@Pos2) As VarChar(8000))
  Set @Pos2=@Pos1+1
  Set @Pos1 = @Pos1+1
 End 
 Return
End

Then, you can use it to split the comma delimited string in to seperate records to filter your data.

Ex.

Code:
Create Procedure ExampleX
    @CommaString VarChar(8000)
AS
SET NOCOUNT ON

Declare @Temp Table(Id Integer)

Insert Into @Temp
Select FieldName
From   dbo.Split(@CommaString, ',')

Select * 
from   SomeTable
       Inner Join @Temp As T
         On SomeTable.IdField = T.Id

-George

Strong and bitter words indicate a weak cause. - Fortune cookie wisdom
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top