Solved

Query Syntax for Optional Parameter

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

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Introduction In the following article I’ll be discussing and demonstrating several different ways of how images can be put on a report. I’m using SQL Server Reporting Services 2008 R2 CTP, more precisely version 10.50.1352.12, but the methods ex…
It is helpful to note: This is a cosmetic update and is not required, but should help your reports look better for your boss.  This issue has manifested itself in SSRS version 3.0 is where I have seen this behavior in.  And this behavior is only see…
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

746 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now