Solved

Query Syntax for Optional Parameter

Posted on 2014-12-12
2
102 Views
Last Modified: 2014-12-12
I have a parameter (@Phrase) that may be filled.  It has properties set to Allow Null.

My issue is with my dataset (query).  I don't know how to make it run if the @Phrase is Null.

Here is my Where clause:

WHERE i.InsuredID in(@ClientID)
AND LossDate between @FromDate and @ToDate
AND co.FileName like '%@Phrase%'  ----- this isn't working when nothing is put into the Parameter.
0
Comment
Question by:Scott Williams
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
2 Comments
 
LVL 65

Accepted Solution

by:
Jim Horn earned 500 total points
ID: 40496637
AND (co.FileName LIKE '%' + @Phrase + '%' OR @Phrase IS NULL)

To test, copy-paste the below into your SSMS..
IF OBJECT_ID('tempdb..#tmp') IS NOT NULL
   DROP TABLE #tmp
GO

CREATE TABLE #tmp (val varchar(100))

INSERT INTO #tmp (val) 
VALUES ('goo'), ('foo'), ('boo'), ('yabba'), ('dabba'), ('doo')

-- Returns only the values LIKE @par when it's populated
Declare @par varchar(100) = 'g'

SELECT val
FROM #tmp
WHERE (val LIKE '%' + @par + '%'  OR @par IS NULL)  

-- Returns all when it's NULL
SET @par  = NULL

SELECT val
FROM #tmp
WHERE (val LIKE '%' + @par + '%'  OR @par IS NULL)  

Open in new window

0
 

Author Closing Comment

by:Scott Williams
ID: 40496664
Thanks a lot Jim!  That's a great way to prove it works!!
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Hi All, I am here to write a simple article to move SSRS (SQL Server Reporting Services) reports from one server to another. When I have faced the same issue to move reports those were developed by developer on development server and now need to …
Introduction Earlier I wrote an article about the new lookup functions (http://www.experts-exchange.com/A_3433.html) that ship with SQL Server 2008 R2.  In this article I’m going to show you another new feature of SSRS 2008 R2, this time in the vis…
I've attached the XLSM Excel spreadsheet I used in the video and also text files containing the macros used below. https://filedb.experts-exchange.com/incoming/2017/03_w12/1151775/Permutations.txt https://filedb.experts-exchange.com/incoming/201…

730 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question