Forums Últimos mensajes - Powered by IBM
 
Tags Palabras claves

Sentencia SQL

01/03/2006 - 11:32 por Kevin | Informe spam
Hola
Mi fuerte es C#, pero se me cruzo esto en SQL y creo que tiene que haber una
forma mas corta de hacerlo. Este es mi codigo de SQL, hay alguna forma de
que si los valores de los parametros son -1 me traiga todos los datos. O
como lo harian?

CREATE PROCEDURE Messages_Get
@MessageId int = -1,
@SenderGender bit = -1,
@Text varchar(15) = -1,
@Number int = -1
As
If @MessageId = -1
If @SenderGender = -1 AND @Text = -1 AND @Number = -1
Select * from Messages
Order By Date Desc
If @SenderGender != -1 AND @Text != -1 AND @Number != -1
Select * from Messages
Where SenderGender = @SenderGender And Text Like @Text And Number =
@Number
Order By Date Desc
If @SenderGender != -1 AND @Text != -1 AND @Number = -1
Select * from Messages
Where SenderGender = @SenderGender And Text Like @Text
Order By Date Desc
If @SenderGender != -1 AND @Text = -1 AND @Number = -1
Select * from Messages
Where SenderGender = @SenderGender
Order By Date Desc
If @SenderGender = -1 AND @Text = -1 AND @Number != -1
Select * from Messages
Where Number = @Number
If @SenderGender = -1 AND @Text != -1 AND @Number = -1
Select * from Messages
Where Text Like @Text

Else
Select * from Messages Where MessageId = @MessageId Order By Date Desc

Gracias
 

Leer las respuestas

#1 carlos
01/03/2006 - 12:29 | Informe spam
hola,
prueba con algo asi

create procedure messages_get
@a int = -1,
@b int = -1,
@c int = -1
as
Select * from tabla where
(@a = -1 or campA = @a) AND
(@b = -1 or campB = @b) AND
(@c = -1 or campC = @c)

Más eficiente aún, es utilizando COALESCE (mira en los BOL)
Espero te sirva.




"Kevin" <@> escribió en el mensaje
news:
Hola
Mi fuerte es C#, pero se me cruzo esto en SQL y creo que tiene que haber


una
forma mas corta de hacerlo. Este es mi codigo de SQL, hay alguna forma de
que si los valores de los parametros son -1 me traiga todos los datos. O
como lo harian?

CREATE PROCEDURE Messages_Get
@MessageId int = -1,
@SenderGender bit = -1,
@Text varchar(15) = -1,
@Number int = -1
As
If @MessageId = -1
If @SenderGender = -1 AND @Text = -1 AND @Number = -1
Select * from Messages
Order By Date Desc
If @SenderGender != -1 AND @Text != -1 AND @Number != -1
Select * from Messages
Where SenderGender = @SenderGender And Text Like @Text And Number > @Number
Order By Date Desc
If @SenderGender != -1 AND @Text != -1 AND @Number = -1
Select * from Messages
Where SenderGender = @SenderGender And Text Like @Text
Order By Date Desc
If @SenderGender != -1 AND @Text = -1 AND @Number = -1
Select * from Messages
Where SenderGender = @SenderGender
Order By Date Desc
If @SenderGender = -1 AND @Text = -1 AND @Number != -1
Select * from Messages
Where Number = @Number
If @SenderGender = -1 AND @Text != -1 AND @Number = -1
Select * from Messages
Where Text Like @Text

Else
Select * from Messages Where MessageId = @MessageId Order By Date Desc

Gracias


Preguntas similares