tags:

views:

24

answers:

2

On SQL Server I am trying to be able to select * records from a table with four parameters, in some cases the incoming parameter will be a certain string value 'Select', in that case I would like to select * from the specified field.

Does anyone know of a good way to handle this?

(
 @mParameter varchar(50) = Null,
 @tParameter varchar(50) = Null,
 @gParameter int = Null,
 @nParameter varchar(255) = Null
)

as



Select
  *

From
  TableA

Where

If @mParameter = 'Select' then
  M = @mParameter


If @tParameter = 'Select' then
AND
  T = @tParameter

If @gParameter = 'Select'then
AND
  G = @gParameter

If @nParameter = 'Select' then
AND
  N = @nParameter
+1  A: 

Update 2

Try this:

Select *
From TableA
Where
M = isnull(@mParameter, M)
and T = isnull(@tParameter, T)
and G = isnull(@gParameter, G)
and N = isnull(@nParameter, N)
Denis Valeev
Thank you for your response, But this does not seem to work.
John
In .NET I send a null parameter if a value from a dropdown list is 'Select', If the SP recieves a null param then I would like to not include that parameter in teh query
John
@John See my update.
Denis Valeev
@John No that doesn't make sense! haha I updated the update with the older version of my answer.
Denis Valeev
Thanks Denis, This is returning results.
John
@John: if this answer is the one you want, "accept" it (click the check mark under the number of votes)
egrunin
Ok, no problem.
John
A: 
SELECT *
FROM YourTable
WHERE (@mParameter = 'M' OR @mParameter IS NULL)
AND (@tParameter = 'T' OR @tParameter IS NULL)
AND (@gParameter = 123 OR @gParameter IS NULL)
AND (@nParameter = 'N' OR @nParameter IS NULL)
Muhammad Kashif Nadeem