Wednesday, 24 August 2016

Dynamic sql query

No comments
CREATE procedure [dbo].[GetAll]
(
@countryId int,
@Title varchar(max),
@City varchar(max),
@MinimumInvestment int=null,
@MaximumInvestment int=null,
@InvestorRoleId int,
@GrowthStage varchar(max)
)
as
begin
declare @Query varchar(max)
set @Query ='
 select * from [dbo].[Opportunities]
where
CountryId =isnull('+case when @countryId is null then 'NULL' else cast(@countryId as varchar) end+',CountryId)
and City  like isnull('+case when @City is null then 'NULL' else cast(@City  as varchar) end+',City)
and Title  like isnull('''+case when @Title is null then 'NULL' else cast(@Title as varchar) end+''',Title)
and MinimumInvestment>=isnull('+case when @MinimumInvestment is null then 'NULL' else cast(@MinimumInvestment  as varchar) end+',MinimumInvestment)
and MaximumInvestment>=isnull('+case when @MaximumInvestment is null then 'NULL' else cast(@MaximumInvestment  as varchar) end+',MaximumInvestment)
and InvestorRoleId = '+cast(@InvestorRoleId as varchar) +'
and GrowthStageId in ('+case when @GrowthStage is null then 'GrowthStageId' else @GrowthStage end+')'

execute(@Query)
end