I am still learning SQL and I am wondering if there is any way to set a variable to all instead of any specific value. I would want something like that which is useful for me for testing purposes. I know this is how it works.
DECLARE @sku AS VARCHAR(30)
SET @sku = 'ProductA'
Is there anyway I can keep the value inside a variable open. Basically something like this.
DECLARE @sku AS VARCHAR(30)
SET @sku = '%'
or
DECLARE @sku AS VARCHAR(30)
SET @sku LIKE '%'
I am not exactly sure how it works in variables. I tried finding it but couldn't find something that fulfills my purpose. Basically I keep changing the values for the variables between specific value to %. Any suggestions would be appreciated.
Added:
DECLARE @sku AS VARCHAR(30) = '%'
DECLARE @name AS VARCHAR(40) = '%'
select * from table1
where sku = @sku
select * from table2
where sku = @sku
select * from table3
where name = @name
Basically in the above sample query, I have to commenting and uncommenting the where clause in 3 different tables. There is a situation where I put value in @sku on the top and I can use the where clause in the select statements. For testing purposes, I have to comment the where statements but for that I need to do that in 3 different queries. Is there anyway if I can just put the filter on the top instead of commenting all 3 where clauses. Does it make sense?
CodePudding user response:
If your goal to use an optional "all"-value for a parameter, you can do it like this:
DECLARE @sku nvarchar(100) = '%'; -- or any other token
...
WHERE @sku IN (field, '%')
This evaluates to: if @sku is %
, the condition is always true and returns all rows.
For any other value, it only filters the rows where field
equals the parameter.