Solved

Query Syntax for Optional Parameter

Posted on 2014-12-12
2
100 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
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

Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

Question has a verified solution.

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

Suggested Solutions

This code started out as a fix for a customer that had incoming data that was hunderds of numbers and words long that was to fit in one column. The problem was that the customer did not want to split words or numbers when wrapping in the column. …
Hi, I have heard from my friends that it’s not possible to create Label Printing report using SSRS. I am amazed after hearing this words not possible in SSRS. I googled lot and found that it is possible to some of people know about the Report Bui…
This Micro Tutorial will teach you how to censor certain areas of your screen. The example in this video will show a little boy's face being blurred. This will be demonstrated using Adobe Premiere Pro CS6.
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…

786 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