Solved

using variables in whereclause

Posted on 2012-03-29
7
257 Views
Last Modified: 2012-03-29
Hi,
  I have something like below in my stored procedure

IF @physicianID = 0 OR @physicianID IS NULL
BEGIN
SET @whereClause = 'requestedby=@physicianID
            and examdate>=@startDate
            and examdate<=@endDate'
END
ELSE
BEGIN
SET @whereClause ='examdate>=@startDate
            and examdate<=@endDate'
END

and I used the variable @whereCluase like below

select
            examdate,
            patient_no
      from exams
      where @whereClause
      group by examdate,patient_no
Can I do like this? or please let me know how can I do that .

Thank you
0
Comment
Question by:Sthokala
[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
  • 3
  • 3
7 Comments
 
LVL 56

Expert Comment

by:HainKurt
ID: 37783272
after your code do his

declare @sql varchar(max) = 'select ... from ...' + @whereClause
exec @sql
0
 
LVL 56

Expert Comment

by:HainKurt
ID: 37783288
oops, you need to work on this part too

SET @whereClause = 'requestedby=@physicianID
            and examdate>=@startDate
            and examdate<=@endDate'
>>>>
SET @whereClause = 'requestedby=' + @physicianID +
          ' and examdate>= ''' + @startDate + ''''
          ' and examdate<= ''' + @endDate + ''''
0
 
LVL 56

Expert Comment

by:HainKurt
ID: 37783311
and I guess there is logical error in your code "if... then ... else..." logic should be reversed...

so, final structure should be something like this

declare @whereClause varchar(max)
declare @startDate varchar(12)
declare @endDate varchar(12)
declare @physicianID int

IF isNull(@physicianID,0) = 0
BEGIN 
  SET @whereClause ='examdate >= ''' + @startDate + ''' and examdate <= ''' + @endDate + ''''
END
ELSE
BEGIN
  SET @whereClause = 'requestedby=' + @physicianID + ' and examdate>= ''' + @startDate + ''' and examdate<= ''' + @endDate + ''''
END

declare @sql varchar(max) = 'select ... from ...' + @whereClause
exec @sql

Open in new window

0
Get free NFR key for Veeam Availability Suite 9.5

Veeam is happy to provide a free NFR license (1 year, 2 sockets) to all certified IT Pros. The license allows for the non-production use of Veeam Availability Suite v9.5 in your home lab, without any feature limitations. It works for both VMware and Hyper-V environments

 
LVL 69

Expert Comment

by:Scott Pletcher
ID: 37783340
You have two choices:
    1.  Use one query, which tests the variable and column as needed.  
         This may not produce an optimal query plan every time it run.
    2.  Use dynamic SQL, which will produce an optimal query plan, but is more work
         to set up **and requires specific authorities being granted *directly* to the id
         used to run the SQL code**.


--1.
SELECT
            examdate,
            patient_no
      FROM dbo.exams
      WHERE
          (@physicianID = 0 OR @physicianID IS NULL OR requestedby = @physicianID) AND
          examdate>=@startDate and
          examdate<=@endDate'
      GROUP BY
          examdate, patient_no
0
 
LVL 69

Accepted Solution

by:
Scott Pletcher earned 500 total points
ID: 37783367
--2.

DECLARE @sql nvarchar(max)

SET @sql = '
SELECT
            examdate,
            patient_no
      FROM dbo.exams
      WHERE
          examdate>=@startDate AND
          examdate<=@endDate
'

IF @physicianID > 0
    SET @sql = @sql + ' AND
           requestedby = ' + CAST(physicianID AS varchar(10))

SET @sql = @sql + '
       GROUP BY
          examdate, patient_no'

EXEC sp_executesql @sql, N'@startDate datetime, @endDate datetime', @startDate, @endDate
0
 

Author Comment

by:Sthokala
ID: 37783530
Hi,
  Thank you for your comments.  I tried below way

DECLARE @sql nvarchar(max)

SET @sql = ' INSERT INTO #TmpMUStatus
   SELECT count(*), (SELECT name from users where user_no='+CAST(@physicianID AS varchar(10))+') as physicianName,null,null,null,null,null,null,null,null,null,null,NULL,NULL from(
      SELECT
            examdate,
            patient_no
      FROM exams WHERE
          examdate>='+LEFT(CONVERT(VARCHAR, @startDate, 120), 10)
+' AND
          examdate<='+LEFT(CONVERT(VARCHAR, @endDate, 120), 10)

IF @physicianID > 0
    SET @sql = @sql + ' AND
           requestedby = ' + CAST(@physicianID AS varchar(10))

SET @sql = @sql + '
        GROUP BY examdate,patient_no) AS SourceQuery'
EXEC @sql


I am getting below error

Msg 203, Level 16, State 2, Procedure GenerateMUStats, Line 54
The name ' INSERT INTO #TmpMUStatus
   SELECT count(*), (SELECT name from users where user_no=73408) as physicianName,null,null,null,null,null,null,null,null,null,null,NULL,NULL from(
      SELECT
            examdate,
            patient_no
      FROM exams WHERE
          examdate>=2012-01-01 AND
          examdate<=2012-05-05 AND
           requestedby = 73408
        GROUP BY examdate,patient_no) AS SourceQuery' is not a valid identifier.
0
 
LVL 69

Expert Comment

by:Scott Pletcher
ID: 37783579
EXEC (@sql) -- the parens are required


Since you want pass to the date values in, you also need additional quotes:

...
FROM exams WHERE
          examdate>='''+LEFT(CONVERT(VARCHAR, @startDate, 112), 8)
+''' AND
          examdate<='''+LEFT(CONVERT(VARCHAR, @endDate, 112), 8) + ''''
...
0

Featured Post

PeopleSoft Has Never Been Easier

PeopleSoft Adoption Made Smooth & Simple!

On-The-Job Training Is made Intuitive & Easy With WalkMe's On-Screen Guidance Tool.  Claim Your Free WalkMe Account Now

Question has a verified solution.

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

In this article I will describe the Copy Database Wizard method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
There are cases when e.g. an IT administrator wants to have full access and view into selected mailboxes on Exchange server, directly from his own email account in Outlook or Outlook Web Access. This proves useful when for example administrator want…
In this video, viewers are given an introduction to using the Windows 10 Snipping Tool, how to quickly locate it when it's needed and also how make it always available with a single click of a mouse button, by pinning it to the Desktop Task Bar. Int…

623 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