Help With Optional Parameter Query With IN Statements

Aug 24, 2007

I have a query with 17 separate, optional, parameters. I have declared each parameter = NULL so that I can test for NULL in the case that the user didn€™t not pass in the parameter.

I am new enough to SQL Server that I am having difficulty building the WHERE clause with all of these optional parameters.

One solution I was advised on by a well paid SQL programmer, was to use a string in the stored proc and dynamically build the WHERE clause and exec it at the end of the sp. But the whole point of a stored proc is that it can be compiled and cached to make it faster, yet the string approach makes it have to compile every time it€™s run! Not a good solution, but maybe it€™s the best I can do . . .

I have tried many different approaches using different functions, etc. but I€™ve hit a brick wall. Any help in sorting it out with YOUR techniques would be greatly appreciated:

1. To add the parameter to the WHERE clause and test for NULL I€™ve used the COALESCE function such as €œWHERE table.fieldname = COALESCE(@Param, table.fieldname)€?. This works well if there is only one item in the parameter, but in the case that I pass multiple items to the parameter, it completely fails.

2. To handle multiple items, for example, if @Param = €˜3,7,98€™ (essentially, a csv separated list of keys)

Code SnippetWHERE table.fieldname IN(COALESCE(@Param, table.fieldname))


doesn€™t work because @Param needs to be parsed from a string into an array of integers in the parameter. So, I am using a UDF I discovered to parse the multi-item parameter. The UDF can be found at http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnsqlmag01/html/TreatYourself.asp and it returns a table variable that can be used in an IN statement. So I€™m using


Code SnippetISNULL(table.fieldname, 0) IN (SELECT value FROM dbo.fn_Split(@Param,€™,€™))



which works brilliantly in my WHERE statement AS LONG AS @Param ISN€™T NULL. So how do I test for NULL first and still use this approach to multi-item parameters?

I€™ve tried


Code SnippetWHERE @Param IS NULL OR ISNULL(table.fieldname, 0) IN (SELECT value FROM dbo.fn_Split(@Param,€™,€™))


and though it works, the OR causes it to slow way down as it compares every record for the OR. (It slows down by approximately 800%.) The other thing I tried was


Code SnippetISNULL (table.fieldname, 0) IN (CASE WHEN @Param IS NULL THEN ISNULL(table.fieldname, 0) ELSE (SELECT value FROM dbo.fn_Split(@Param,€™,€™)))



This fails with €œSubquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression€? due to the multiple values in the parameter. (I can€™t understand why the line without the CASE statement works, but the CASE line doesn€™t!)

Am I even on the right track, cuz this is driving me mad and I just need a way to deal with optional multi-item parameters in an IN statement? HELP!








View 4 Replies


ADVERTISEMENT

Optional Parameter In Sql Query

Nov 6, 2005

Hi All,I have a stored proc which looks like this.Create ....(@id int,@ud int,@td int=0)if @td=0select bkah from asdf where id=@id and ud=@udelseselect bkah from asdf where id=@id and ud=@ud and td=@td---------------------------------I am wondering if i could replace if condition with the following lineselect bkah from asdf where id=@id and ud=@udand ( @td<>0 and td>@td )IS sql server 2000 smart enough not to use the td>@td in the query if@td is 0Thanks all

View 3 Replies View Related

Optional Parameter

Apr 13, 2006

Hello,
Is it possible to define optional parameters for a stored procedure?
What I want is to create a search with about 8 parameters, but most users will only use 3 or 4, so It would be nice If I could only provide the used parameters in my code. And have sql give the unused parameters a default value (possibly %)
thx.

View 4 Replies View Related

SPROC With Optional Parameter

Jan 16, 2004

I need to use a parameter in a stored procedure that is optional and if it is optional I need all records returned, even if there is an entry in the field that the parameter is appllied to. Is this possible? I know I can assign a default value. but the value in the field could be one of many choices. I want to be able to specify a choice and have only those records returned or leave it blank and return all records.

Thanks for any help,

View 4 Replies View Related

Is There Is Any Direct Way To Set Optional Parameter

May 12, 2008



hi all,
I am using SQL reporting services 2005, i like to have a parameter as optional, is there is any diresct way to set a parameter as optional without setting through the default value.

View 6 Replies View Related

SqlDataSource Optional Parameter Problem

Dec 5, 2005

Hi, I'm having some issues with the SqlDataSource. I want to use it
to
populate a GridView, but using an optional parameter to filter the
results.

This is what I have right now (hopefully haven't made any typos
- can't
copy/paste):

<asp:SqlDataSource ID="test1" runat="server"
SelectCommand="SELECT * FROM
SomeTable WHERE (@MyParam IS NULL OR MyColumn =
@MyParam) ORDER BY
SomeColumn" ConnectionString="<%
ConnectionStrings:MyConnString %>" >
<SelectParameters>
 
<asp:ControlParameter Name="MyParam"
ControlID="DropDownList1"
PropertyName="SelectedValue" Type="String"
ConvertEmptyStringToNull="True"
DefaultValue=""
/>
</SelectParameters>
</asp:SqlDataSource>

<asp:DropDownList
ID="DropDownList1" runat="server" AutoPostBack="True">
  <asp:ListItem
Selected="True" Value="">All</asp:ListItem>
 
<asp:ListItem>AnotherValue</asp:ListItem>
 
<asp:ListItem>SomeElse</asp:ListItem>
 
<asp:ListItem>Whatever</asp:ListItem>
</asp:DropDownList>

<asp:GridView
ID="GV" runat="server" DataSourceID="test1"
AutoGenerateColumns="False"
DataKeyNames="SomeID"
  <columns>
    <asp:BoundField
DataField="SomeColumn" HeaderText="A Title"
SortExpression="SomeColumn"
/>
   (more bound columns here...)
 
</columns>
</asp:GridView>

When I test the SQL query in
the query designer it works (returns only rows
having the value passed as a
parameter when one is specified, otherwise it
returns all rows), so it seems
like that part is OK. The "All" (as in
"return all"/no filtering) entry in
the DropDownList has a value of a zero
lenght string, and the
ControlParameter has the convert empty string to null
to true (and the
default value is the same), so it should get converted to a
null when "All"
is selected, hence returning all rows. But it doesn't work.
It works fine for
all the entries with text, but the zero lenght string
somehow doesn't work -
I get no results at all instead of it returning all
rows (but the query
itself worked fine when I tested it).

What am I missing? I just can't
find what I'm doing wrong. Any ideas/hints?
(I also need to do the same with
an ObjectDataSource, so hopefully I can get
this to work!) I can't think of
an easy way to find out if the zero lenght
string gets converted to a null or
not (I've even tried adding OR @MyParam =
'' to the query and it still didn't
work....) Right now I'm stuck....

(Also posted this question on microsoft.public.dotnet.framework.adonet newsgroup)

Thanks a lot in advance for the
replies!

Carl B.

View 1 Replies View Related

Can A Stored Procedure Parameter Be Optional

Mar 7, 2006

I want the procedure to check for the existence of a paramter and if it isthere, it will process these instructions, otherwise it will process theseinstructions. Any ideas? Thanks for your advice.Regards,CK

View 7 Replies View Related

Optional Command Line Parameter

Jan 17, 2006





Hello,



I want to use an optional parameter at the command line for my package.

I planned to make the first task a script which simply checks the variable (which is a string), and if it is empty, go one way, and if it is not, go another way. Is the best to go?



Many thnaks in advane

View 4 Replies View Related

Optional Parameter On Joined Field Which Could Be Null?!

Jul 20, 2005

I have two tables: eg. a person-table (no nulls allowed), with an idand so on, and a person_course table (an intermediate table in amany-to many relationship between person table and courses tables),with two fields person_id and course_id.But I want to make ONE multipurpose stored procedure, which has ONLYoptional parameters on all fields in the person table AND the fieldcourse_id in the person_course table.I have no problems making optional parameters on the person table (eg.P.ID=ISNULL(@PersonID, P.ID ) ) BUT the problem is, when I try to addan optional parameter on the field course_id it dosn't produce theright results. Some times the course_id is null (because some personshavn't joined a class yet).Is there a way around it?Ole S. Pedersen

View 1 Replies View Related

Multivalued Report Parameter That Is Integer And Should Be Optional

May 23, 2007

Hello,

my problem is that i have a integer report parameter that must be multivalued. The parameter is populated by query. The thing is that in the beginning, there is no data in the dataset of the specific parameter. The table which is source to the dataset will br populated after some time from an XML.





Reporting services prompts the user to select a value for the parameter. But there is no value to select, yet. I cannot have leave blank because it is a string and not an int and i cannot have null because the parameter is multivalued. Any suggestions?





Thank you for your time and help!





/luskan

View 4 Replies View Related

Reporting Services :: Optional Parameter Usage In SSRS

Oct 15, 2015

In my report I have two parameters PID and patientName, but user want to enter either PID or patientName. When I preview the report user can only enter one parameter not both. Is there any way  to create two parameter available but users  can enter only one parameter value?Here is my report layout and query I used for that report. These two parameters comes from  one column 'String_NVC' as from query and column name 'Description' as from the report layout.

SELECT Username_NVC AS Username,
String_NVC,
Time_DT AS UserActionDateandTime,
FROM test

[code]...

View 8 Replies View Related

Reporting Services :: Check Box To Use As A Group By Parameter (Optional) In SSRS

May 13, 2015

I have a ssrs report with Name, phone ,state and city as columns. I have check box as one of my parameter(optional). If user checks that checkbox then it should group by state, if checkbox is left blank no need to do any grouping. How can i do this in ssrs 2012.

View 3 Replies View Related

SQL Query Multiple/Optional Feilds

Dec 3, 2004

Hello Group
I am having a little trouble with a search. I have 12 checkbox controls and 12 textbox controls. I want to be able to choose which textbox to query from. Most of the time the search may be from one or a couple of textboxes. My problem is I can get the SQL String right. Below is what I have for a string. I know I could write an SQL string for every possible combination and put in all 144 in a SELECT CASE, but I would think there is an easier way to do this. Is there anything that would let me build a SQL string depending what checkbox are checked true?


Dim SQL_SL As String = "SELECT * FROM BuildZone" & _
" WHERE Parcel = '" & strPercelS & "'" & _
" ORDER BY Parcel Asc" & _
" SQL_SL As String = SELECT * FROM BuildZone" & _
" WHERE fldNameLast = '" & strNameLastS & "'" & _
" UNION" & _
" SQL_SL As String = SELECT * FROM BuildZone" & _
" WHERE fldDateMonth = " & intDateYearS & "" & _
" AND fldDateYear = " & intDateYearS & "" & _
" UNION" & _
" SQL_SL As String = SELECT * FROM BuildZone" & _
" WHERE fldNameLast = '" & strNameLastS & "'" & _
" UNION" & _
" SQL_SL As String = SELECT * FROM BuildZone" & _
" WHERE fldPermitNum = " & intPermitS & "" & _
" UNION" & _
" SQL_SL As String = SELECT * FROM BuildZone" & _
" WHERE fldStructureType = " & intStructureTypeS & "" & _
" UNION" & _
" SQL_SL As String = SELECT * FROM BuildZone" & _
" WHERE fldConstructionCost >= " & intCCost1S & "" & _
" AND fldConstructionCost <= " & intCCost2S & "" & _
" UNION" & _
" SQL_SL As String = SELECT * FROM BuildZone" & _
" WHERE fldRange = " & intRangeS & "" & _
" AND fldTownship = " & intTownshipS & "" & _
" AND fldSection = " & intSectionS & "" & _
" UNION" & _
" SQL_SL As String = SELECT * FROM BuildZone" & _
" WHERE fldZoningDistricts = " & intZoneS & "" & _
" UNION" & _
" SQL_SL As String = SELECT * FROM BuildZone" & _
" WHERE fldTwsp = " & intTwspS & "" & _
" UNION" & _
" SQL_SL As String = SELECT * FROM BuildZone" & _
" WHERE fldRWD = " & intRWDS & "" & _
" UNION" & _
" SQL_SL As String = SELECT * FROM BuildZone" & _
" WHERE fldWW = " & intWWS & "" & _
" UNION" & _
" SQL_SL As String = SELECT * FROM BuildZone" & _
" WHERE fldAccessApplic = " & intAccessAppS & ""

Thanks

View 2 Replies View Related

Search Query With Optional Parameters

Jun 12, 2006

I need to create a stored procedure that will search some tables.

The stored procedure will be passed some parameters that may or may not have a value.

I have googled the best way to do this.
I found this post as an example: Optional Search Parameters

and also found this example : Optional Parameters in T-sQL

I am trying to figure out the best way to do this.

In the past I would build a dynamic query like the following.


SQL Code:






Original
- SQL Code




CREATE PROCEDURE [dbo].[Search_Results]

@SUBCITY VarChar(100) = 'Any'

AS

------------------------------------------------------------------------------------------------------
Declare @SUBCITYString Varchar(200)
If @SUBCITY <> 'Any'
Begin
Set @SUBCITYString = ' AND (Table1.SUBCITY LIKE ''' + @SUBCITY + '%'') '
End
Else
Begin
Set @SUBCITYString = ''
End
-----------------------------------------------------------------------------------------------------

Declare @SQLString As Varchar(500)
Set @SQLString = 'SELECT*

FROMTable1

WHERE Table1.ID IS NOT NULL
' + @SUBCITYString + '

ORDER BY Column ASC'

Execute (@SQLString)

GO






CREATE PROCEDURE [dbo].[Search_Results]  @SUBCITY VarChar(100) = 'Any' AS ------------------------------------------------------------------------------------------------------DECLARE @SUBCITYString Varchar(200)IF @SUBCITY <> 'Any' BEGIN  SET @SUBCITYString = ' AND (Table1.SUBCITY  LIKE ''' + @SUBCITY + '%'') 'ENDELSE BEGIN SET @SUBCITYString = '' END----------------------------------------------------------------------------------------------------- DECLARE @SQLString AS Varchar(500)SET @SQLString = '  SELECT    *                            FROM  Table1               WHERE  Table1.ID IS NOT NULL                ' + @SUBCITYString +  '            ORDER BY Column ASC' Execute (@SQLString) GO


However this is really cumbersome to create and is not fun debugging!

Does one of these ways have an advantage over the other? Or is there another way to do this?

Thank you!

View 2 Replies View Related

Parameter For Multiple Where Statements

Sep 5, 2007

I'm hoping someone out there has a creative solution for my scenario. I have the report code below. I want to create a parameter that allows the user to select which where statement to use in the report. Then I want to use the corresponding where description below ( ex: @WHEREDESC1 ) in my header which will describe (in laymen's terms) which parameter was chosen and what is being reported on.

Has anyone achieved this or have an idea how it may be done?



DECLARE @WHEREDESC1 VARCHAR(50), @WHEREDESC2 VARCHAR(50), @WHEREDESC3 VARCHAR(50),

@WHEREDESC4 VARCHAR(50), @WHEREDESC5 VARCHAR(50)

SET @WHEREDESC1 = 'SRM Admitting and Principal Diagnosis do not match'

SET @WHEREDESC2 = 'SRM and AMPFM Admit dates do not match'

SET @WHEREDESC3 = 'SRM and AMPFM Discharge dates do not match'

SET @WHEREDESC4 = 'SRM and AMPFM Visit Type Codes do not match'

SET @WHEREDESC5 = 'SRM and AMPFM DRG codes do not match'

SELECT LEFT(srm.EPISODES.ADMISSION_DATE, 11) AS SRM_Admit_DT, ampfm.rpt_AdtVisit.AdmitDate AS AMPFM_Admit_DT,

LEFT(srm.EPISODES.EPISODE_DATE, 11) AS SRM_Disch_DT, ampfm.rpt_AdtVisit.DischDate AS AMPFM_Disch_DT,

srm.EPISODES.EPISODE_TYPE AS SRM_Visit_Type, ampfm.rpt_AdtVisit.VisitTypeCode AS AMPFM_Visit_Type,

srm.EPISODES.CHARGES AS SRM_Charges, ampfm.rpt_VisitFinancial.TotCharges AS AMPFM_Charges,

ampfm.rpt_VisitFinancial.VisitChargesActive AS AMPFM_Active_Charges, ampfm.rpt_AdtVisit.PatientFullName,

srm.CDMAB_DRG_INFO.DRG_NUMBER AS SRM_Drg, ampfm.rpt_InsuranceDrg.InsDrg AS AMPFM_Drg,

ampfm.rpt_AdtVisit.Complaint AS AMPFM_Admit_Dx, srm.cdmab_base_info.ADM_DX_CODE, srm.cdmab_base_info.ADM_DX_DESC,

srm.cdmab_base_info.PRIN_DX_CODE, srm.cdmab_base_info.PRIN_DX_DESC, srm.EPISODES.ACCOUNT_NUMBER,

srm.EPISODES.MEDREC_NO

FROM srm.EPISODES INNER JOIN

ampfm.rpt_AdtVisit ON srm.EPISODES.ACCOUNT_NUMBER = ampfm.rpt_AdtVisit.AccountNumber INNER JOIN

ampfm.rpt_VisitFinancial ON ampfm.rpt_AdtVisit.IntOOS = ampfm.rpt_VisitFinancial.IntOOS INNER JOIN

ampfm.rpt_InsuranceDrg ON ampfm.rpt_AdtVisit.IntOOS = ampfm.rpt_InsuranceDrg.IntOOS AND

ampfm.rpt_AdtVisit.VisitTypeCode = ampfm.rpt_InsuranceDrg.VisitTypeCode INNER JOIN

srm.CDMAB_DRG_INFO ON srm.EPISODES.EPISODE_KEY = srm.CDMAB_DRG_INFO.EPISODE_KEY INNER JOIN

srm.cdmab_base_info ON srm.EPISODES.EPISODE_KEY = srm.cdmab_base_info.EPISODE_KEY

--WHERE srm.cdmab_base_info.ADM_DX_CODE <> srm.cdmab_base_info.PRIN_DX_CODE

--WHERE srm.EPISODES.ADMISSION_DATE <> ampfm.rpt_AdtVisit.AdmitDate

--WHERE srm.EPISODES.EPISODE_DATE <> ampfm.rpt_AdtVisit.DischDate

--WHERE srm.EPISODES.EPISODE_TYPE <> ampfm.rpt_AdtVisit.VisitTypeCode

--WHERE srm.CDMAB_DRG_INFO.DRG_NUMBER <> ampfm.rpt_InsuranceDrg.InsDrg

Order By srm.EPISODES.ACCOUNT_NUMBER

View 7 Replies View Related

Transact SQL :: Query For Multiple Optional Conditions?

Jun 1, 2015

I have following query. Now I want to change this in such a way that if Condition 1 satisfies then it should not go to next condition ,if not then should go to next. Similarly the same format till condition 4.

select * from table where
IND = 'Y'
and
(
(STATE = @STATE and LOB =@LOB and COMPANY=@COMPANY)--Condition 1
OR
(STATE = @STATE and LOB =@LOB)--Condition 2
OR
(STATE = @STATE and COMPANY=@COMPANY)--Condition 3
OR
(STATE = @STATE)--Condition 4
)

View 4 Replies View Related

Parameter Information Cannot Be Derived From SQL Statements With Sub-select Queries

Apr 24, 2006

Parameter Information cannot be derived from  SQL statements with sub-select queries. Set Parameter information before preparing command.

Here's the query:

update GCDE_SEQ
set LAST_NO =  (select  max(FLD_NO)
   from PONL_FLD)
 ,UPDT_USER = ?
 ,UPDT_DT = getdate()
where SEQ_NM = 'FLD_NO'

Why can't Execute SQL Task handle this simple query? I figure i can use 2 SQL Execute SQL Task, one to get the max into a var, and the other to do the updating. However, this is alot of trouble since i'm having this almost exact query in alot of places. Any way around this?

View 8 Replies View Related

Concatenating Parameter Values && Text; Nested CASE Statements

Sep 27, 2007

Hello.  I'm trying to reduce some code in my stored procedure and I'm running into lots of errors.  I'm somewhat of a novice with SQL and stored procedures so any help would be beneficial.
I have a SP that gets a page of user data and is also called when sorting by one of the columns (this data is placed in a repeater, btw).  I quickly learned that I wasn't able to pass in string parameters the way I had hoped in order to handle the ORDER BY and direction (ASC/DESC) so I'm trying to work around this.
So far I've tried the following with many errors.WITH Users AS (
SELECT ROW_NUMBER() OVER (ORDER BY CASE WHEN @OrderBy='FirstName' AND @Direction='DESC' THEN (FirstName + ' DESC')
WHEN @OrderBy='FirstName' THEN FirstName
WHEN @OrderBy='LastName' AND @Direction='DESC' THEN (LastName + ' DESC')
WHEN @OrderBy='LastName' THEN LastName
END
) AS Row,
UserID, FirstName, LastName, EmailAddress, [Role], Active, LastLogin, DateModified, ModifiedBy, ModifiedByName
FROM
vRF_Users
)

SELECT UserID, FirstName, LastName, EmailAddress, [Role], Active, LastLogin, DateModified, ModifiedBy, ModifiedByName
FROM Users
WHERE Row BETWEEN @StartRowIndex AND @EndRowIndex
 
I've tried a combination of similar things with parenthesises, without, doing "THEN FirstName DESC" without concatenating anything, etc.
I also tried: DECLARE @OrderByDirection varchar(32)
DECLARE @DESC varchar(4)
SET @DESC = ' DESC'

IF @Direction = 'DESC'
BEGIN
SET @OrderByDirection = (@OrderBy + @DESC)
END
And then writing my case statemet like this:ORDER BY CASE WHEN @Direction='DESC' THEN @OrderByDirection
ELSE @OrderBy
ENDObviously this didn't work either.  Is there any way to gracefully accomplish this or do I just have to use a bunch of if/else statements and lots of redundant code to evaluate all my @OrderBy and @Direction parameters???
 
Thanks in advance,
Jen

View 26 Replies View Related

SQL Server Admin 2014 :: Estimated Query Plan For A Stored Procedure With Multiple Query Statements

Oct 30, 2015

When viewing an estimated query plan for a stored procedure with multiple query statements, two things stand out to me and I wanted to get confirmation if I'm correct.

1. Under <ParameterList><ColumnReference... does the xml attribute "ParameterCompiledValue" represent the value used when the query plan was generated?

<ParameterList>
<ColumnReference Column="@Measure" ParameterCompiledValue="'all'" />
</ParameterList>
</QueryPlan>
</StmtSimple>

2. Does each query statement that makes up the execution plan for the stored procedure have it's own execution plan? And meaning the stored procedure is made up of multiple query plans that could have been generated at a different time to another part of that stored procedure?

View 0 Replies View Related

Using IIF Statements Inside A Query?

Jan 30, 2008



Hi,

I'm wondering if it is possible to use IF statements in a query, for example if this was my query:

SELECT Asset, Source, Val1, Val2, Val3
FROM tableA

Say the sign of the Vals is always positive, but based on if the Source field is null i want to make the Vals negative.
Could I do something like this:

SELECT Asset, Source, (IIF Source = null, Val1*-1, Val1), (IIF Source = null, Val2*-1, Val2), (IIF Source = null, Val3*-1, Val3)
FROM tableA


When I try something like this it doesn't work, is there a way to do this in a query?

Thanks.

View 3 Replies View Related

Numbering The SQL Query Statements

Jan 4, 2007

Using the TOAD application for Oracle, I am able to number the SQL query lines for readability. Can the same be done for SQL Server 2005?

View 4 Replies View Related

Can We Combine These 3 Statements Into One Single Query

May 13, 2004

SELECT 1 as id,COUNT(name) as count1
INTO #temp1
FROM emp

SELECT 1 as id,COUNT(name) as count2
INTO #temp2
FROM emp
WHERE name <>' ' AND name IS NOT NULL OR name <> NULL


SELECT (cast(b.count2 as float)/cast(a.count1 as float))*100 AS per_non_null_names
FROM #temp1 a INNER JOIN #temp2 ON a.id=b.id

View 9 Replies View Related

Maximum UNION Statements In A Query

Dec 17, 2005

Wondering if there is a physical or realistic limitation to the numberof UNION statements I can create in a query? I have a client withapprox 250 tables - the data needs to be kept in seperate tables, but Ineed to be filtering them to create single results sets. Each tableholds between 35,000 - 150,000 rows. Should I shoot myself now?lq

View 15 Replies View Related

Sql Query Statements &&amp; ADO.NET Connected Classes.

Oct 9, 2007

Hi all,

Do I still need to write the .sql query statements (in SSMS) if I use the ADO.NET connected classes like GetSchema method or the DbDataAdaptor Object?

I'm very new to Visual Studio 2005 & SQL Server 2005..

Thanks!

View 3 Replies View Related

How Should I Write This Query Wiht Case Statements

Oct 5, 2007

Hi
  I have a stored procedure and i am trying to add case statements to them.. but i am getting an Error. which is
Msg 125, Level 15, State 3, Procedure udf_EndDate, Line 34
Case expressions may only be nested to level 10.
 
And This is my sproc-- ================================================
-- Template generated from Template Explorer using:
-- Create Scalar Function (New Menu).SQL
--
-- Use the Specify Values for Template Parameters
-- command (Ctrl-Shift-M) to fill in the parameter
-- values below.
--
-- This block of comments will not be included in
-- the definition of the function.
-- ================================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:<Author,,Name>
-- Create date: <Create Date, ,>
-- Description:<Description, ,>
-- =============================================
Create FUNCTION [dbo].[udf_EndDate] (@PeriodId int)
RETURNS datetime
AS

BEGIN
DECLARE
@Month int,
@Year char(4)

SELECT
@Month = [Month],
@Year = Cast([Year] as char(4))
FROM
Period
WHERE
PeriodId = @PeriodId

RETURN
CASE @Month WHEN 1 THEN '1/31/' + @Year ELSE
CASE @Month WHEN 2 THEN '2/28/' + @Year ELSE
CASE @Month WHEN 3 THEN '3/31/' + @Year ELSE
CASE @Month WHEN 4 THEN '4/30/' + @Year ELSE
CASE @Month When 5 Then '5/31/' + @Year ELSE
CASE @Month When 6 Then '6/30/' + @Year ELSE
CASE @Month When 7 Then '7/31/' + @Year ELSE
CASE @Month When 8 Then '8/31/' + @Year ELSE
CASE @Month When 9 Then '9/30/' + @Year ELSE
CASE @Month When 10 Then '10/31/' + @Year ELSE
CASE @Month When 11 Then '11/30/' + @Year ELSE
CASE @Month When 12 Then '12/31/' + @Year ELSE null END
END
END
END
END
END
END
END
END
END
END
END
END

Any help will be appreciated.
 
Regards
Karen

View 8 Replies View Related

Using SQL Query Columns In Select Case Statements

Jun 5, 2006

I am using Visual Web Developer Express 2005 as a test environment.  I have it connected to a SQL 2000 server.  I would like to use a Select Case Statement with the name of a column from a SQL Query as the Case Trigger.  Assuming the SQLDataSource is named tCOTSSoftware and the column I want to use is Type, it would look like the following in classic ASP:
Select Case tCOTSSoftware("Type")
      Case 1
         execute an SQL Update Command
     Case 2
         execute a different SQL Update Command
End Select
What would a comparable ASP.Net (Visual Basic) statement look like?  How would I access the column name used in the SQLDataSource?

View 6 Replies View Related

Multiple FROM Statements Inside A Single Query?

Mar 21, 2012

what is the logic in multiple "FROM" statements inside a single query?

View 1 Replies View Related

Select Query Involving Many JOIN Statements.

Mar 19, 2008

Is it possible to have an AND within an inner join statment? The below query works, except for the line marked with --*--.

The error I get is the "multipart identifier pregovb.cellname could no be bound", which usually means that SQL server can't find what I'm talking about, but it's puzzling, as I've created the temp table with such a column in it.

Is there a different way i should be structuring my select statement?

SELECT [Survey Return].SurveyReturnID, '1', #temp_pregovb.paidDate, #temp_pregovb.email
FROM #temp_pregovb, [Survey Return]
INNER JOIN SelectedInvited ON
[Survey Return].SelectedID = SelectedInvited.SelectedID
--*-- AND [SelectedInvited].cellref=#temp_pregovb.cellname

INNER JOIN [panelist Contact]
ON SelectedInvited.PanelistID=[Panelist Contact].PanelistID
WHERE
[panelist contact].email=#temp_pregovb.email
AND SelectedInvited.CellRef IN (
SELECT surveycell
FROm [Survey Cells]
WHERe SurveyRef='5')

View 3 Replies View Related

How To Use Query Analyzer To Find The Most Efficient One In Many Select Statements?

Nov 8, 2006

Hi, everyone.

I have read a lot of topics about execution plan for query, but I got little.
Please give me some help with examples for comparing different select statements to find the best efficient select statement.

Thank you very much.

View 4 Replies View Related

SQL Server 2012 :: Adding 2 COUNT Statements Results In Heavy Query

Jan 28, 2014

These separate COUNT queries are very fast:

SELECT COUNT(id) as viewcount from location_views WHERE createdate>DATEADD(dd,-30,getdate()) AND objectid=357
SELECT COUNT(id)*2 as clickcount FROM extlinks WHERE createdate>DATEADD(dd,-30,getdate()) AND objectid=357

But I want to add the COUNT statements, so this is what I did:

select COUNT(vws.id)+COUNT(lnks.id)*2 AS totalcount
FROM location_views vws,extlinks lnks
WHERE (vws.createdate>DATEADD(dd,-30,getdate()) AND vws.objectid=357)
OR
(lnks.createdate>DATEADD(dd,-30,getdate()) AND lnks.objectid=357)

Turns out the query becomes immensely slow. There must be something I'm doing wrong here which results in such bad performance, but what is it?

View 7 Replies View Related

SQL Security :: Database Level Audit - Query Parameters For SELECT Statements

Aug 31, 2015

I have setup a Database Audit Specification as follows:

Audit Action Type: SELECT | Object Class: DATABASE | Object Name: SHOPDB | Principal Name: public

Now, when I perform a SELECT query with a bound parameter such as:

SELECT * FROM myTable WHERE name='queryname'

What I see through the Audit Logs is something like:

SELECT * FROM myTable WHERE name='@1'

I understand that it is by design that we cannot see these parameters throught Database Level Auditing. I would like to know whether it is possible to see these parameters by any other means using

(1) SQL Server Enterprise Edition,
(2) SQL Server Standard Edition, or
(3) by an external tool.

View 9 Replies View Related

Optional Relationship

Dec 18, 2006

Hi, how can i make optional relationship?
for example: In table A, there is column 1, column 2, column3. In table B, there is column 4, column 5 and column 6.
 column 1 and column 2 are primary keys for table A and table B. The relationships between table A and table B are column 2 and column 5; column3 and column 6. but optional (ie. when data exists in column 2, then column3 is null)
 how can i set the relationship? because one of the columns data is null each time, error always occurs.

View 6 Replies View Related

Optional Inner Joins

Nov 27, 2004

I have a select proc that will take a bunch or criteria parameters. Based on how many are not null I would like to decide how many inner joins to do.
for example:

select H1.Priceid as HotelPriceId,H2.Priceid as AirPriceId, H1.VendorPackageId from
(
select HA.PriceId, HA.VendorPackageId from Criteria HA Inner Join
(
select VendorPackageId from ValidVendorPackages
where Vendor = 'SBT'
and Sitecode = 'system'
and PackageType = 'AHCF'
)HB on HA.VendorPackageId = HB.VendorPackageId
and
(
CriteriaId in
(
select CriteriaID from ValidItemCriteria
where Destination = 'LAS'
and LengthOfStay = 5
and Ages = 'A2'
and ComponentType = @ComponentType_1
and ValidItemType = @ValidItemType_1
and ItemValue = @ItemValue_1
)
)

)H1 INNER JOIN
(
select HA.PriceId, HA.VendorPackageId from Criteria HA Inner Join
(
select VendorPackageId from ValidVendorPackages
where Vendor = 'SBT'
and Sitecode = 'system'
and PackageType = 'AHCF'
)HB on HA.VendorPackageId = HB.VendorPackageId
and
(
CriteriaId in
(
select CriteriaID from ValidItemCriteria
where Destination = 'LAS'
and LengthOfStay = 5
and Ages = 'A2'
and ComponentType = @ComponentType_2
and ValidItemType = @ValidItemType_2
and ItemValue = @ItemValue_2
)
)
)H2 on H1.Priceid = H2.priceId Inner Join
(
select HA.PriceId, HA.VendorPackageId from Criteria HA Inner Join
(
select VendorPackageId from ValidVendorPackages
where Vendor = 'SBT'
and Sitecode = 'system'
and PackageType = 'AHCF'
)HB on HA.VendorPackageId = HB.VendorPackageId
and
(
CriteriaId in
(
select CriteriaID from ValidItemCriteria
where Destination = 'LAS'
and LengthOfStay = 5
and Ages = 'A2'
and ComponentType = @ComponentType_3
and ValidItemType = @ValidItemType_3
and ItemValue = @ItemValue_3
)
)
)H3 on H2.Priceid = H3.priceId

if values are only passed in from @ComponentType_1,@ValidItemType_1,@ItemValue_1 I dont want to do any inner joins.

If its passed in for @ComponentType_1,@ValidItemType_1,@ItemValue_1 & @ComponentType_2,@ValidItemType_2,@ItemValue_2 I want to do the first Inner Join.

and of course if I get all 3 sets of criteria I want to do both the inner joins.
I know I can cut and past this thing 3 times with an if statement but that isn't going to be practical.

View 14 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved