Execute Dynamic SQL commands in SQL Server

In some applications having hard-coded SQL statements is not appealing, because of the dynamic nature of the queries being issued against the database server. Because of this sometimes there is a need to dynamically create a SQL statement on the fly and then run that command. This can be done quite simply from the application perspective where the statement is built on the fly whether you are using ASP.NET , ColdFusion or any other programming language. But how do you do this from within a SQL Server stored procedure? SQL Server offers a few ways of running a dynamically built SQL statement. These ways are: Writing a query with parameters Using EXEC Using sp_executesql Writing a query with parameters This first approach is pretty straightforward if you only need to pass parameters into the WHERE clause of your SQL statement. Let’s say we need to find all records from the Customers table where City = ‘London’. This can be done easily as the following example shows. ...

Convert Row to column as csv in sql

Raw Data:

id name services

1 Joe AA
1 Joe AB
1 Joe AC
2 Judy GH
2 Judy GC
3 Kevin AA
3 Kevin GH

Result Set:

id name services

1 Joe AA, AB, AC
2 Judy GH, GC
3 Kevin AA, GH

If you have MSSQL2K, then the most performant (and arguably most elegant) way woud be to use a user-defined function:

Let’s prepare some sample data

create table t1(id int, name varchar(10), services varchar(10))  
insert into t1 values(1,'Joe' ,'AA')  
insert into t1 values(1,'Joe' ,'AB')  
insert into t1 values(1,'Joe' ,'AC')  
insert into t1 values(2,'Judy' ,'GH')  
insert into t1 values(2,'Judy' ,'GC')  
insert into t1 values(3,'Kevin','AA')  
insert into t1 values(3,'Kevin','GH')  

Now let’s create a function named my_comma_sep, as shown below

create  function  my_comma_sep ( @id int) returns varchar(4000) as  
begin  
declare @result varchar(4000)  
set @result = ''  
select @result = @result  
+ case when len(@result)>0 then ',' else '' end  
+ services  
from t1  
where id = @id  
return @result  
end  

Now you can use the function like this:

select id,name, dbo.my_comma_sep(id)  
from (select distinct id,name from t1) x  

…or like this:

select id, max(name), dbo.my_comma_sep(id)  
from t1 group by id  

… or like this:

select id, name, dbo.my_comma_sep(id)  
from t1 group by id,name  

… and the result:

1 Joe AA,AB,AC
2 Judy GH,GC
3 Kevin AA,GH

Comments

Popular posts from this blog

Check If Temporary Table Exists

Multiple NULL values in a Unique index in SQL

How To search entire database?