开发者

Microsoft SQL CASE statement in where clause using LIKE

开发者 https://www.devze.com 2023-01-14 19:05 出处:网络
I once used a scenario where I did a SQL where clause like this: where BranchName = CASE WHEN @pBranch <> \'\' then @pBranch else BranchName end

I once used a scenario where I did a SQL where clause like this: where BranchName = CASE WHEN @pBranch <> '' then @pBranch else BranchName end

this is to say we're doing a branch name lookup, but this statement has to cater for the LIKE clause somehow. We need to be able to say 'If the pBranch parameter was provided then do a like search else ignore that part of the WHERE clause.

Any clues?

开发者_StackOverflow社区Thanks, Jacques


you could say:

SELECT *
FROM dbo
WHERE @pBranch = '' OR BranchName = @pBranch

This basically says that if you pass in '' to @pBranch, then all results will be displayed, otherwise, if you pass in something else, it will search by your argument


try

Where BranchName Like IsNull(@Branch, BranchName)


actually I think the answer I was looking for is as follows:

... where o.BranchName like case when @pBranchName <> '' then @pBranchName else o.BranchName end ...


where @pBranch = '' or BranchName like @pBranch

(add the wildcards to the appropriate spot in the like clause)

this will work for numbers, not just strings - so if you passed in an int parameter as a 0 or a value, you would do:

where @param = 0 or DBField = @param
0

精彩评论

暂无评论...
验证码 换一张
取 消