Showing posts with label SQL server. Show all posts
Showing posts with label SQL server. Show all posts

Tuesday, August 2, 2011

Execute query with string

Today, I got a strange requirement to have the query as query string to execute, and tried various ways and found that the simplest way to do this is

Declare @temp Varchar(500)
Set @temp = ‘Select * From Employees’
Exec (@temp)

the above code will help us in adding or removing the clause from the query

Monday, November 30, 2009

Split in SQLServer

Create function [dbo].[fn_Split](
@String nvarchar (4000),
@Delimiter nvarchar (10)
)
returns @ValueTable table (pos int,[Value] nvarchar(4000))
begin
declare @NextString nvarchar(4000)
declare @Pos int
declare @NextPos int
declare @CommaCheck nvarchar(2)
declare @index int
declare @lenstring int

set @index=1
set @lenstring= len(@Delimiter)
set @NextString = ''
set @CommaCheck = right(@String,@lenstring)
set @String = @String + @Delimiter

set @Pos = charindex(@Delimiter,@String)
set @NextPos =@lenstring
while (@pos <> 0)
begin
set @NextString = substring(@String,1,@Pos - 1)
insert into @ValueTable (pos, [Value]) Values (@index,@NextString)
set @String = substring(@String,@pos +@lenstring,len(@String))
set @NextPos = @Pos
set @pos = charindex(@Delimiter,@String)
set @index = @index +1
end

return
end