Tuesday, July 14, 2009

Function to Concatenate Strings In SQL

Alter function dbo.ConcatAreaName(@pincode varchar(20))
RETURNS varchar(2000)
As
Begin
Declare @var varchar(2000)
set @var=''
Select @var = @var +'#'+ areaname from area where pincode=@pincode group by areaname
return @var
End

To Get the Result from Function :
Concatenate Areaname on the basis of pincode :
select distinct pincode, dbo.ConcatAreaName(pincode) from area where pincode='124505'
select distinct top 10 pincode, dbo.ConcatAreaName(pincode) from area

1 comment:

Varun Bhagat said...

BETTER USE COALESCE FUNCTION... AN EXMPLE I DONE IN GETIT
HOPE THIS WILL BE HELPFUL TO YOU

***************************

CREATE function [dbo].[csv_keyword](@l3code varchar(20))
RETURNS varchar(2000)
As
BEGIN
Declare @var varchar(2000)
set @var=''
Select @var = COALESCE(@var+ ', ', '') + CAST(keyword AS varchar(2000))
FROM keyword
where level3code=@l3code
return @var
END