質問

I have the below SQL code snippet and I want to select sales from all customers by manipulating the value of the @Customer parameter. Is there any way to do this in SQL Server 2008 R2? I've tried setting @Customer = '%' but obviously that didn't work since there is no LIKE operator.

I only want to manipulate the parameter because there will be other times where I will need to select only a single customer. Is there such a thing as using an IF/ELSE in the WHERE clause?

DECLARE @Customer varchar(5) = ''

SELECT *
FROM SalesData
WHERE Customer=@Customer
役に立ちましたか?

解決

Is there such a thing as using an IF/ELSE in the WHERE clause

Absolutely, there is a CASE expression - not only in the WHERE clause, but also in other parts of your query. However, a more common approach is to use logical expressions in the WHERE clause that force SQL Server to take one condition or the other depending on the parameter setting.

my condition would be if @Customer = '' then select all

If you would like to select all customers when the parameter is set to empty, or select all customers where the parameter is not set, you can do this:

SELECT *
FROM SalesData
WHERE @Customer = ''
   OR  Customer = @Customer

If @Customer is set to '', the first clause of the OR expression will be TRUE for all rows, so all customers would be returned. However, when @Customer is non-empty, the second part of the expression would be evaluated.

他のヒント

Not quite sure how you need to perform search

But can try something like below

SELECT *
FROM SalesData
WHERE Customer like '%' + @Customer + '%'

Or

SELECT *
FROM SalesData
WHERE (LEN(@Customer)>0 AND Customer =@Customer)
     OR (LEN(@Customer)=0)

In here I havent trim assuming you always pass ''. But you can always use LEN(LTRIM(RTRIM(@Customer)))

If you default @Customer to NULL rather than '' then you could just have

WHERE Customer = ISNULL(@Customer, Customer)
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top