sql server - Setting a variable to a certain value or default to all values in a column -


sorry if heading clear. trying create stored procedure :

create procedure pro1 @a nvarchar = null, @b nvarchar =null select * table1 parameter1 = '1' , parameter2 = @a go 

above not actual code hope explains trying achieve. selecting on 2 parameters. 'parameter2' depends on variable @a. challenge have if @a remains null @ execution; want select statement search on values of parmeter2 if 'and' statement not there. write if else statement execute different selects hoping set @a sort of wildcard value this? maybe : 'like []'?

create procedure dbo.pro1 -- use schema prefix when creating objects!   @a nvarchar(32) = null -- 32 should match data type of parameter2 column begin -- wrap body , indent readability   set nocount on; -- should turn off done_in_proc messages    select columns -- please name columns instead of select *     dbo.table1 -- use schema prefix when referencing objects     (parameter2 = @a or @a null); -- semi-colons please! end go 

in cases may find if have lot of these optional parameters, sql server compile plan 1 set of parameters , plan not beneficial different parameters. may want this:

create procedure dbo.pro1   @a nvarchar(32) = null begin   set nocount on;    declare @sql nvarchar(max);    set @sql = n'select columns dbo.table1 1=1';    if @a not null     set @sql += ' , parameter2 = @a';    exec sp_executesql @sql,     n'@a nvarchar(32)',     @a; end go 

Comments

Popular posts from this blog

How to mention the localhost in android -

php - Calling a template part from a post -

c# - String.format() DateTime With Arabic culture -