Friday, March 30, 2012

How to simplify my storeprocedure

Hello,if have more than two condition(City,State), how to simplify
following storeprocedure.(without Too much [if ... else] and duplicat
code),thanks.
CREATE PROCEDURE selectAuthors @.City Varchar(20),@.State Varchar(2)
AS
IF @.City<>''
IF @.State<>''
SELECT *
FROM authors where city=@.City AND state=@.State
Else
SELECT *
FROM authors where city=@.City
Else
IF @.State<>''
SELECT *
FROM authors where state=@.State
Else
SELECT *
FROM authorsDoes this help?
=====
DECLARE @.City VARCHAR(30)
DECLARE @.State VARCHAR(10)
SET @.City = 'Menlo Park'
SET @.State = ''
SELECT * FROM authors WHERE
city = CASE WHEN @.City = '' OR @.City IS NULL THEN city ELSE @.City END
AND
state = CASE WHEN @.State = '' OR @.State IS NULL THEN state ELSE @.State
END
=====
--
HTH,
SriSamp
Email: srisamp@.gmail.com
Blog: http://blogs.sqlxml.org/srinivassampath
URL: http://www32.brinkster.com/srisamp
"Simon" <w007@.seed.net.tw> wrote in message
news:OwuB%23X%23RGHA.1236@.TK2MSFTNGP11.phx.gbl...
> Hello,if have more than two condition(City,State), how to simplify
> following storeprocedure.(without Too much [if ... else] and duplicat
> code),thanks.
>
> CREATE PROCEDURE selectAuthors @.City Varchar(20),@.State Varchar(2)
> AS
> IF @.City<>''
> IF @.State<>''
> SELECT *
> FROM authors where city=@.City AND state=@.State
> Else
> SELECT *
> FROM authors where city=@.City
> Else
> IF @.State<>''
> SELECT *
> FROM authors where state=@.State
> Else
> SELECT *
> FROM authors
>
>|||Thank you for your help
"SriSamp" <ssampath@.sct.co.in> bl
news:eqxiiI$RGHA.5780@.TK2MSFTNGP10.phx.gbl g...
> Does this help?
> =====
> DECLARE @.City VARCHAR(30)
> DECLARE @.State VARCHAR(10)
> SET @.City = 'Menlo Park'
> SET @.State = ''
> SELECT * FROM authors WHERE
> city = CASE WHEN @.City = '' OR @.City IS NULL THEN city ELSE @.City END
> AND
> state = CASE WHEN @.State = '' OR @.State IS NULL THEN state ELSE @.State
> END
> =====
> --
> HTH,
> SriSamp
> Email: srisamp@.gmail.com
> Blog: http://blogs.sqlxml.org/srinivassampath
> URL: http://www32.brinkster.com/srisamp
> "Simon" <w007@.seed.net.tw> wrote in message
> news:OwuB%23X%23RGHA.1236@.TK2MSFTNGP11.phx.gbl...
>sql

No comments:

Post a Comment