Showing posts with label clause. Show all posts
Showing posts with label clause. Show all posts

Thursday, March 29, 2012

Case statement 'Operator' in Where clause

i have a sp like this
--
@.operator int --(1=smaller,2=bigger)
@.price decimal(18,2)
select id,price
from company
where (price case @.operator when 1 then <@.price when 2 then >@.price end )
how can i accomplish this?
thnxdeclare @.operator int,
@.price decimal(18,2)
select ID, Price
from Company
where (price < @.price and @.operator = 1 )
and (price > @.price and @.operator = 2)
But if you have this in a Store procedure
declare @.operator int,
@.price decimal(18,2)
if @.operator = 1
begin
select ID, Price
from Company
where price < @.price
end
else if @.operator = 2
begin
select ID, Price
from Company
where price > @.price
end
Also with the logic that you have if the price is the same you will
never see it.
So you need to do this if was in procedure
declare @.operator int,
@.price decimal(18,2)
if @.operator = 1
begin
select ID, Price
from Company
where price <= @.price
end
else if @.operator = 2
begin
select ID, Price
from Company
where price >= @.price
end|||On Wed, 25 Jan 2006 13:38:01 -0800, henk wrote:

>i have a sp like this
>--
>@.operator int --(1=smaller,2=bigger)
>@.price decimal(18,2)
>select id,price
>from company
>where (price case @.operator when 1 then <@.price when 2 then >@.price end )
>--
>how can i accomplish this?
>thnx
Hi Henk,
IF @.operator = 1
SELECT id, price
FROM company
WHERE price < @.price
ELSE
SELECT id, price
FROM company
WHERE price > @.price
Hugo Kornelis, SQL Server MVP|||You can use either options as follows
declare @.operator int --(1=smaller,2=bigger)
declare @.price decimal(18,2)
set @.operator = 1 -- 2
set @.price = 10.05
-- Option A
declare @.cmd varchar(8000)
set @.cmd = 'select id, price from company where price '+ case @.operator when
1 then '< @.price' else '> @.price' end
exec (@.cmd)
-- Option B
if @.operator = 1
select id
,price
from company
where price < @.price
if @.operator = 2
select id
,price
from company
where price >@.price
"henk" wrote:

> i have a sp like this
> --
> @.operator int --(1=smaller,2=bigger)
> @.price decimal(18,2)
> select id,price
> from company
> where (price case @.operator when 1 then <@.price when 2 then >@.price end )
> --
> how can i accomplish this?
> thnx
>|||thanks for your reply
i realy would like to do this in one statment without making use of if-else.
the reason behind this is that i have multiple operators for multiple
columns and it realy gets complex with 4 or 5 operators.
is it possible or do i have to use the if-else senario?
"Amiller" wrote:

> declare @.operator int,
> @.price decimal(18,2)
>
> select ID, Price
> from Company
> where (price < @.price and @.operator = 1 )
> and (price > @.price and @.operator = 2)
> But if you have this in a Store procedure
> declare @.operator int,
> @.price decimal(18,2)
>
> if @.operator = 1
> begin
> select ID, Price
> from Company
> where price < @.price
> end
> else if @.operator = 2
> begin
> select ID, Price
> from Company
> where price > @.price
> end
>
> Also with the logic that you have if the price is the same you will
> never see it.
> So you need to do this if was in procedure
> declare @.operator int,
> @.price decimal(18,2)
>
> if @.operator = 1
> begin
> select ID, Price
> from Company
> where price <= @.price
> end
> else if @.operator = 2
> begin
> select ID, Price
> from Company
> where price >= @.price
> end
>|||DECLARE @.operator int
DECLARE @.price decimal (18,2)
SET @.price = 17.99
--To find items that are less than @.price, set @.operator to 1
--To find items that are more than @.price, set @.operator to 2
SELECT id, price
FROM company
WHERE
CASE
WHEN price - @.price > 0 THEN 2
WHEN price - @.price <= 0 THEN 1
END
= @.operator
The following was tested on Northwind
USE Northwind
GO
DECLARE @.operator int
DECLARE @.price money
SET @.operator = 1
SET @.price = 17.95
select productid, unitprice
FROM Products
WHERE
CASE
WHEN UnitPrice > @.price THEN 2
WHEN UnitPrice < @.price THEN 1
END = @.operator
"henk" wrote:

> i have a sp like this
> --
> @.operator int --(1=smaller,2=bigger)
> @.price decimal(18,2)
> select id,price
> from company
> where (price case @.operator when 1 then <@.price when 2 then >@.price end )
> --
> how can i accomplish this?
> thnx
>|||I am not sure if the first statement will work i have never tried
something like that. I would go with the if else and comment all layers
so you know what one does what.|||thank you all for your helpfull replys.
i think i go with the Mark 's solution. that is exactly what i wanted.
thank you once again.
"Mark Williams" wrote:
> DECLARE @.operator int
> DECLARE @.price decimal (18,2)
> SET @.price = 17.99
> --To find items that are less than @.price, set @.operator to 1
> --To find items that are more than @.price, set @.operator to 2
> SELECT id, price
> FROM company
> WHERE
> CASE
> WHEN price - @.price > 0 THEN 2
> WHEN price - @.price <= 0 THEN 1
> END
> = @.operator
>
> The following was tested on Northwind
> USE Northwind
> GO
> DECLARE @.operator int
> DECLARE @.price money
> SET @.operator = 1
> SET @.price = 17.95
> select productid, unitprice
> FROM Products
> WHERE
> CASE
> WHEN UnitPrice > @.price THEN 2
> WHEN UnitPrice < @.price THEN 1
> END = @.operator
> --
>
> "henk" wrote:
>|||Just to clean things up
DECLARE @.operator int
DECLARE @.price decimal (18,2)
SET @.price = 17.99
--To find items that are less than @.price, set @.operator to 1
--To find items that are more than @.price, set @.operator to 2
SELECT id, price
FROM company
WHERE
CASE
WHEN price > @.price THEN 2
WHEN price <= @.price THEN 1
END
= @.operator
Not sure why I did the whole price - @.price > 0 thing when the above is much
cleaner.
"henk" wrote:

> thank you all for your helpfull replys.
> i think i go with the Mark 's solution. that is exactly what i wanted.
> thank you once again.
>|||yeah i got it,
your the man man!!!!:)sql

CASE Statement in Where Clause?

Can anyone tell me if it's possible to use a Case statement in a Where
clause, and if so, the proper syntax?

J.R.
Largo SQL Tools
The Finest Collection of SQL Tools Available
http://www.largosqltools.com"Largo SQL Tools" <support@._REMOVE_largosqltools.com> wrote in message
news:v5adnTcJ84Mdbh-iXTWJiw@.buckeye-express.com...
> Can anyone tell me if it's possible to use a Case statement in a Where
> clause, and if so, the proper syntax?
> J.R.
> Largo SQL Tools
> The Finest Collection of SQL Tools Available
> http://www.largosqltools.com

CASE is an expression, not a statement, and, as such, returns a value.
It can indeed be used in a WHERE clause. For example,

SELECT *
FROM T
WHERE col1 = CASE WHEN col2 < col3
THEN col2
ELSE col3
END

Regards,
jag|||Sure you can. Unlike procedural languages, CASE in SQL is an expression. You
can use almost any kind of expressions in WHERE clause (aggregate functions
are exceptions).

This is an example of using CASE in WHERE clause:

select *
from YourTable
where SomeColumn = case
when Condition1 then Value1
when Condition2 then Value2
else Value3
end

Shervin

"Largo SQL Tools" <support@._REMOVE_largosqltools.com> wrote in message
news:v5adnTcJ84Mdbh-iXTWJiw@.buckeye-express.com...
> Can anyone tell me if it's possible to use a Case statement in a Where
> clause, and if so, the proper syntax?
> J.R.
> Largo SQL Tools
> The Finest Collection of SQL Tools Available
> http://www.largosqltools.comsql

CASE statement in WHERE clause problem

Hello,
I would like to achieve the following within an stored procedure.
SELECT * FROM TableX WHERE ID = 1
OR
SELECT * FROM TableX WHERE ID IS NOT NULL
How can I solve this by using a condition in my WHERE clause?
eg.
//////
CREATE PROCEDURE TestID
@.ID INT
AS
SELECT * FROM TableX
WHERE ID =
CASE
WHEN @.ID IS NOT NULL THEN @.ID
ELSE NOT NULL
END
////
The problem is the ' NOT ' NULL in the ELSE Path
If I skip the ELSE Path then it will be implicitly NULL
Thanks for any help,
RemcoHi,
Try this
SELECT * FROM TableX WHERE ID = 1 OR ID IS NOT NULL
Hth
"Remco" <rembo_r@.hotmail.com> wrote in message
news:eGlfZa3DFHA.1296@.TK2MSFTNGP10.phx.gbl...
> Hello,
> I would like to achieve the following within an stored procedure.
> SELECT * FROM TableX WHERE ID = 1
> OR
> SELECT * FROM TableX WHERE ID IS NOT NULL
> How can I solve this by using a condition in my WHERE clause?
>
> eg.
> //////
> CREATE PROCEDURE TestID
> @.ID INT
> AS
> SELECT * FROM TableX
> WHERE ID =
> CASE
> WHEN @.ID IS NOT NULL THEN @.ID
> ELSE NOT NULL
> END
> ////
> The problem is the ' NOT ' NULL in the ELSE Path
> If I skip the ELSE Path then it will be implicitly NULL
> Thanks for any help,
> Remco
>|||Hello Remco,

> Hello,
> I would like to achieve the following within an stored procedure.
> SELECT * FROM TableX WHERE ID = 1
> OR
> SELECT * FROM TableX WHERE ID IS NOT NULL
> How can I solve this by using a condition in my WHERE clause?
>
if you want criteria:
1. @.ID != null --> ID = @.ID
2. @.ID IS NULL --> ID IS NOT NULL
then:
WHERE
(@.ID IS NOT NULL AND ID = @.ID)
OR (@.ID IS NULL AND ID IS NOT NULL)
Lasse Vgsther Karlsen
http://www.vkarlsen.no/
mailto:lasse@.vkarlsen.no
PGP KeyID: 0x0270466B|||this should get you started on how to do that.
http://www.aspfaq.com/show.asp?id=2501
"Remco" wrote:

> Hello,
> I would like to achieve the following within an stored procedure.
> SELECT * FROM TableX WHERE ID = 1
> OR
> SELECT * FROM TableX WHERE ID IS NOT NULL
> How can I solve this by using a condition in my WHERE clause?
>
> eg.
> //////
> CREATE PROCEDURE TestID
> @.ID INT
> AS
> SELECT * FROM TableX
> WHERE ID =
> CASE
> WHEN @.ID IS NOT NULL THEN @.ID
> ELSE NOT NULL
> END
> ////
> The problem is the ' NOT ' NULL in the ELSE Path
> If I skip the ELSE Path then it will be implicitly NULL
> Thanks for any help,
> Remco
>
>|||Try,
SELECT * FROM TableX
WHERE [ID] = @.id or (@.id is null and [id] is null)
AMB
"Remco" wrote:

> Hello,
> I would like to achieve the following within an stored procedure.
> SELECT * FROM TableX WHERE ID = 1
> OR
> SELECT * FROM TableX WHERE ID IS NOT NULL
> How can I solve this by using a condition in my WHERE clause?
>
> eg.
> //////
> CREATE PROCEDURE TestID
> @.ID INT
> AS
> SELECT * FROM TableX
> WHERE ID =
> CASE
> WHEN @.ID IS NOT NULL THEN @.ID
> ELSE NOT NULL
> END
> ////
> The problem is the ' NOT ' NULL in the ELSE Path
> If I skip the ELSE Path then it will be implicitly NULL
> Thanks for any help,
> Remco
>
>|||
SET ANSI_NULLS ON
SELECT * FROM TableX
WHERE ID =
CASE
WHEN @.ID IS NOT NULL THEN @.ID
ELSE ID
END
Roji. P. Thomas
Net Asset Management
https://www.netassetmanagement.com
"Remco" <rembo_r@.hotmail.com> wrote in message
news:eGlfZa3DFHA.1296@.TK2MSFTNGP10.phx.gbl...
> Hello,
> I would like to achieve the following within an stored procedure.
> SELECT * FROM TableX WHERE ID = 1
> OR
> SELECT * FROM TableX WHERE ID IS NOT NULL
> How can I solve this by using a condition in my WHERE clause?
>
> eg.
> //////
> CREATE PROCEDURE TestID
> @.ID INT
> AS
> SELECT * FROM TableX
> WHERE ID =
> CASE
> WHEN @.ID IS NOT NULL THEN @.ID
> ELSE NOT NULL
> END
> ////
> The problem is the ' NOT ' NULL in the ELSE Path
> If I skip the ELSE Path then it will be implicitly NULL
> Thanks for any help,
> Remco
>|||Reading your post again, I realized that what you want is:
select * from tablex
where ([id] = @.id) or (@.id is null and [id] is not null)
AMB
"Alejandro Mesa" wrote:
> Try,
> SELECT * FROM TableX
> WHERE [ID] = @.id or (@.id is null and [id] is null)
>
> AMB
> "Remco" wrote:
>|||"Remco" <rembo_r@.hotmail.com> wrote in message
news:eGlfZa3DFHA.1296@.TK2MSFTNGP10.phx.gbl...

> eg.
> //////
> CREATE PROCEDURE TestID
> @.ID INT
> AS
> SELECT * FROM TableX
> WHERE ID =
> CASE
> WHEN @.ID IS NOT NULL THEN @.ID
> ELSE NOT NULL
> END
> ////
Possibly (untested):
SELECT * FROM TableX where ID = COALESCE(@.ID,ID)
Good Luck,
Jim|||"James Goodwin" <jim.goodwin@.midmichigan.org> wrote in message
news:1fdb1$420b726d$432498ca$16254@.allth
enewsgroups.com...
> SELECT * FROM TableX where ID = COALESCE(@.ID,ID)
I think that will fail if ID is null. Better is
SELECT * FROM TableX where ISNULL(ID, '') = ISNULL(@.ID,'')|||"Remco" <rembo_r@.hotmail.com> wrote in message
news:eGlfZa3DFHA.1296@.TK2MSFTNGP10.phx.gbl...
> Hello,
> I would like to achieve the following within an stored procedure.
> SELECT * FROM TableX WHERE ID = 1
> OR
> SELECT * FROM TableX WHERE ID IS NOT NULL
SELECT * FROM TableX WHERE ID IS NOT NULL
satisfies this condition, but I'm gathering that's not what you want. :)

case statement in where clause

I need a SQL statement that selects a specific year (@.yr type int) in the "createddate" column...if this @.yr is equal to 0 then I want to select ALL columns regardless of the year...

This is what I have so far, but it doesnt work...

SELECT * FROM tblUsers
WHERE year(CreatedDate)=CASE
WHEN @.yr<>'0' THEN @.yr
ELSE NOT NULL
END

SELECT * FROM tblUsers
WHERE year(CreatedDate)=CASE WHEN (@.yr= 0) THEN year(CreatedDate) ELSE @.yr END


case statement in where clause

Hello

I want to put a case statement into a where clause but it's not working. Can anybody help, or tell me a better way of doing this

Thanks very much

declare @.param varchar (100)
select @.param = 'mytext

select
colA
,colB
,colC
from
mytable
where
(case
when @.param is null then colA = 'group'
else colA = 'single'
end)I'd suggest using WHERE colA = CASE WHEN @.param IS NULL THEN 'group' ELSE 'single' END-PatP|||No I can't do it like that

I've rewritten what I want, maybe you can hlp with this

declare @.param varchar (100)
select @.param = 'mytext'

select
colA
,colB
,colC
from
mytable
where
(case
when @.param is null then colB = 'group' and colC = 'something'
else colB = 'group' and colC = @.param
end)|||Ok, let's do that dance and move on to:SELECT
colA
, colB
, colC
FROM mytable
WHERE (@.param IS NULL AND colB = 'group' AND colC = 'something')
OR (@.param = colC AND colB = 'group')-PatP

case statement in where clause

I would like to know that may I use case statement in where clause?
If not, are there any other solution to filter my records depends on my
field.
For example
MyType integer, MyDate datetime
MyType MyDate
1 03/24/2005
1 03/20/2005
2 03/24/2005
I want to show MyType one date before today like record 2,but I want to
everything for MyType 2
Are there any solution for this?
Any information is appreciated,
Souris,Try this
Select * from Tablename where id in (select max(id) from tablename
group by date)
Madhivanan|||You can use a case statement in a where clause, but you don't need to for
this example. If you just want to look for myDate on the previous day and
myType = 2 than you would do this:
select * from myTable
where MyDate = convert(varchar,dateadd(d,-1,getdate()),101)
and MyType = 2
If you are looking for ANY myDate prior to today and myType = 2 than:
select * from myTable
where MyDate < convert(varchar,getdate(),101)
and MyType = 2
"souris" wrote:

> I would like to know that may I use case statement in where clause?
> If not, are there any other solution to filter my records depends on my
> field.
> For example
> MyType integer, MyDate datetime
> MyType MyDate
> 1 03/24/2005
> 1 03/20/2005
> 2 03/24/2005
> I want to show MyType one date before today like record 2,but I want to
> everything for MyType 2
> Are there any solution for this?
> Any information is appreciated,
> Souris,
>
>|||Please post DDL, so that people do not have to guess what the keys,
constraints, Declarative Referential Integrity, datatypes, etc. in your
schema are. Sample data is also a good idea, along with clear
specifications.
<<
No. This is because there is no such statement in SQL. There is a
CASE expression which returns a scalar value.
I want to
everything for MyType 2 <<
SELECT my_type, my_date
FROM Foobar
WHERE my_type = 2
OR my_date < CURRENT_TIMESTAMP;
Rows are not records, columns are not fields. You are still using
terminology from a procedural language with a file system and not
thinking in RDBMS yet.|||Thanks millions,
Souris,
"--CELKO--" <jcelko212@.earthlink.net> wrote in message
news:1111763824.117387.95340@.o13g2000cwo.googlegroups.com...
> Please post DDL, so that people do not have to guess what the keys,
> constraints, Declarative Referential Integrity, datatypes, etc. in your
> schema are. Sample data is also a good idea, along with clear
> specifications.
>
> <<
> No. This is because there is no such statement in SQL. There is a
> CASE expression which returns a scalar value.
>
> I want to
> everything for MyType 2 <<
> SELECT my_type, my_date
> FROM Foobar
> WHERE my_type = 2
> OR my_date < CURRENT_TIMESTAMP;
> Rows are not records, columns are not fields. You are still using
> terminology from a procedural language with a file system and not
> thinking in RDBMS yet.
>

Case Statement in Where Clause

If you could help me with my syntax i would really appreciate
it. I'm trying to change the where clause on the fly, but it's
giving me a syntax error.

Hopefully from what I have below you can tell what i'm after

the first part should evaluate a boolean expression, then if true,
search using one field, otherwise
search using a different field

WHERE

Case WHEN @.myCompany = 933
THEN tblClient.companycode = 933 --problem line
ELSE
tblCase.clientcode = @.myClient --problem line
END

And tblCase.status = 'Active'

thank you!!In SQL Server, CASE doesn't conditionally execute statements, it returns an
expression. You might try something like:

WHERE
tblClient.companycode =
CASE
WHEN @.myCompany = 933
THEN 933 ELSE tblClient.companycode END
AND
tblCase.clientcode =
CASE
WHEN @.myCompany < 933
THEN @.myClient ELSE tblCase.clientcode END
AND tblCase.status = 'Active'

--
Hope this helps.

Dan Guzman
SQL Server MVP
<paulmac106@.gmail.comwrote in message
news:1160689816.017843.61740@.i3g2000cwc.googlegrou ps.com...

Quote:

Originally Posted by

If you could help me with my syntax i would really appreciate
it. I'm trying to change the where clause on the fly, but it's
giving me a syntax error.
>
Hopefully from what I have below you can tell what i'm after
>
the first part should evaluate a boolean expression, then if true,
search using one field, otherwise
search using a different field
>
WHERE
>
Case WHEN @.myCompany = 933
THEN tblClient.companycode = 933 --problem line
ELSE
tblCase.clientcode = @.myClient --problem line
END
>
And tblCase.status = 'Active'
>
thank you!!
>

|||Dan Guzman wrote:

Quote:

Originally Posted by

In SQL Server, CASE doesn't conditionally execute statements, it returns
an expression. You might try something like:
>
WHERE
tblClient.companycode =
CASE
WHEN @.myCompany = 933
THEN 933 ELSE tblClient.companycode END
AND
tblCase.clientcode =
CASE
WHEN @.myCompany < 933
THEN @.myClient ELSE tblCase.clientcode END
AND tblCase.status = 'Active'


Another alternative:

WHERE (NOT(@.myCompany = 933) OR tblClient.companycode = 933)
AND (NOT(@.myCompany <933) OR tblCase.clientcode = @.myClient)
AND tblCase.status = 'Active'|||There is no CASE statement in SQL; there is a CASE expression.
Expressions return values. There is no BOOLEAN data type in SQL.
Fields are not anything like columns. Your entire mental model of SQL
is wrong and you are trying to make it work like a procedural language
that you already know.

Also, we prefer to follow ISO-11179 rules for data elements names, so
quit putting that silly, redundant "tbl-" on table names (unless
furniture is actually involved) and start using collective or plural
names (unless the table is not a set or class of entities, but a single
item).

Here is a guess at what you wanted

WHERE ( COALESCE (@.my_company , Clients.company_code) = 933
OR Cases.clientcode = @.my_client)
AND Case.foobar_status = 'Active' -- status is too vague|||I don't understand the necessity of the diatribe, but thanks for the
suggestion.|||This first 2 suggestions worked perfectly. The third offering returned
unwanted records.

Thanks for your help. I really appreciate it.|||>I don't understand the necessity of the diatribe,<<

EDUCATION ! Your approach is wrong and you are going to kill people or
ruin companies until you get a better mindset. Get over your ego and
become professional. It takes six years to become a Union Journeryman
Carpenter in New York State, but newbies expect to do databases
immeidtely after they get MS certificates. Would you like medicine to
work this way?

You are welcome!|||OK, at least that one was funny.

No ego here, I have to admit you peeked my interest. I've been doing
database work for 10 years now. I've managed to avoid killing people
and ruining companies at least up till the time of this posting.

I do always like to learn new things or better ways to do things.

So, having said that, I'm really curious as to who "we" are that you
reference in your original post. And where can I go to get information
on things like "ISO-11179 rules for data elements names" or another
site to fix my mindset?

thanks,
Paul

btw, Boolean is right there in online books

Searched CASE function:

CASE
WHEN Boolean_expression THEN result_expression
[ ...n ]
[
ELSE else_result_expression
]
END|||paulmac106@.gmail.com wrote:

Quote:

Originally Posted by

So, having said that, I'm really curious as to who "we" are that you
reference in your original post. And where can I go to get information
on things like "ISO-11179 rules for data elements names" or another
site to fix my mindset?


Googling "ISO-11179" turns up http://metadata-standards.org/11179/
and in particular http://metadata-standards.org/11179/#11179-5
"Part 5: Naming and Identification Principles, provides guidance for the
identification of administered items. Identification is a broad term
for designating, or identifying, a particular data item. Identification
can be accomplished in various ways, depending upon the use of the
identifier. Identification includes the assignment of numerical
identifiers that have no inherent meanings to humans; icons (graphic
symbols to which meaning has been assigned); and names with embedded
meaning, usually for human understanding, that are associated with the
data item's definition and value domain."

Quote:

Originally Posted by

btw, Boolean is right there in online books
>
Searched CASE function:
>
CASE
WHEN Boolean_expression THEN result_expression
[ ...n ]
[
ELSE else_result_expression
]
END


That's an expression, not a store-able data type. Again, Googling
(SQL "Boolean type") turns up http://troels.arvin.dk/db/rdbms/
and in particular http://troels.arvin.dk/db/rdbms/#data_types-boolean
Standard:

"The BOOLEAN type is optional (has feature ID T031), which is a bit
surprising for such a basic type. However, it seems that endless
discussions of how NULL is to be interpreted for a boolean value is
holding BOOLEAN from becoming a core type.

The standard says that a BOOLEAN may be one of the following literals:

* TRUE
* FALSE
* UNKNOWN or NULL (unless prohibited by a NOT NULL constraint)

The DBMS may interpret NULL as equivalent to UNKNOWN. It is unclear
from the specification if the DBMS must support UNKNOWN, NULL or both
as boolean literals. In this author's opinion, you should forget about
the UNKNOWN literal in order to simplify the situation and let the
normal SQL three-way logic apply.

It's defined that TRUE FALSE (true larger than false)."

MSSQL:

"Doesn't support the BOOLEAN type.

Possible alternative type: the BIT type which may have 0 or 1 (or NULL)
as value. If you insert an integer value other than these into a field
of type BIT, then the inserted value will silently be converted to 1.

Rudy Limeback has some notes
[http://searchoracle.techtarget.com/...stionNResponse/
0,289625,sid41_cid556536_tax301455,00.html]
about oddities with the MSSQL BIT type.

Documentation [http://msdn2.microsoft.com/en-us/library/ms177603.aspx]"|||>where can I go to get information on things like "ISO-11179 rules for data elements names" or another site to fix my mindset? <<

My books and Chris Date's stuff deal with the "mindset problem" -- I
like my books better, but his "What, not How" is a good intro to
thinking in declarations rather then procedures. You can Google
ISO-11179 specs, but my SQL PROGRAMMING STYLE has some practical tips
on using the principles and is eaier to read than "Standard-speak".

Quote:

Originally Posted by

Quote:

Originally Posted by

>btw, Boolean is right there in online books <<


And they are once again wrong. Standard SQL uses <search conditionin
the BNF; we were careful not to say <predicateor <Boolean Expression>
because of the 3-valued logic and the lack of inference rules in SQL.sql

Case statement in Order by clause

Hi

I need a case statement with in the order clause,

There are fields like below

Feild A FieldB LevelA LevelB

xxxx xxxx

xxxx xxxx

xxxx xxxx 3 2

xxxxx xxxx 2 1

xxxxxx xxxxx 1 1

I need to sort LevelA and LevelB first leaving out the null or blank values in the top rows

Feild A FieldB LevelA LevelB

xxxx xxxx 1 1

xxxx xxxx 2 1

xxxx xxxx 3 2

xxxxx xxxx

xxxxxx xxxxx

Thanks

like this:

Code Snippet

create table #t (FieldA varchar(10), FieldB varchar(10), LevelA int, LevelB int)

insert into #t

select 'xxxx', 'xxxx', null, null

union all select 'xxxx', 'xxxx', null, null

union all select 'xxxx', 'xxxx', 3, 2

union all select 'xxxxx', 'xxxx', 2, 1

union all select 'xxxxxx', 'xxxxx', 1, 1

union all select 'xxxxxx', 'xxxxx', 1, 2

union all select 'xxxxxx', 'xxxxx', 1, 3

select *

from #t

order by case when LevelA is not null then 1 else 9 end,

LevelA,

case when LevelB is not null then 1 else 9 end,

LevelB

|||

You can use a CASE expression like below:

order by coalesce(LevelA, power(2., 31)-1), coalesce(LevelB, power(2., 31)-1)

|||Umachandar,

Some readers might why you said "CASE expression," so I'll remark that COALESCE(a,b) is basically the same as CASE WHEN a IS NULL THEN b ELSE a END.

Sowree,

I think the suggestion below will work, and here I've added the requirement that blank values appear last. (If Angel or Beer are number types, they can't be blank, and this code will incorrectly put values of 0 last, because '' is implicitly converted to 0 in the comparison.)

ORDER BY
CASE WHEN a IS NULL OR a = '' THEN 1 ELSE 0 END,
a,
CASE WHEN b IS NULL OR b = '' THEN 1 ELSE 0 END,
b

Your question isn't entirely clear, so you may have to adapt the suggestions to your exact need.

Steve Kass
Drew University
http://www.stevekass.com

Case statement in a where clause

Hi All,
I have a bit of a delema here, that I know someone knows how to do it
properly.
If the value of DSP_IN_HOUSE = 1, I need the where clause to say:
where DSP_IN_HOUSE_IN = F.CollectorDesc
the code I am using is:
left outer join tlkCollector F
on case when DSP_IN_HOUSE = 1 then DSP_IN_HOUSE_IN = F.CollectorDesc
when DSP_IN_HOUSE = 0 then DSP_RE_OPEN_IN = F.CollectorDesc
end
Is this possible without building the where clause dynamically?
TIA,
JoeCASE is an expression that returns a value; it is not a logic flow operator
that allows you to change the meaning and semantics of a query. Assuming
F.CollectorDesc, DSP_IN_HOUSE_IN and DSP_RE_OPEN_IN (curse the people who
named your columns!) are the same data type:
ON F.CollectorDesc = CASE DSP_IN_HOUSE
WHEN 1 THEN DSP_IN_HOUSE_IN
WHEN 0 THEN DSP_RE_OPEN_IN
END
By the way, you should really get in the habit of using aliases on all of
the tables in your join/where clauses. Leaving them out just because
they're the only table with such a column is confusing for other readers /
maintainers of the code, and could bite you if such a column is added to one
of the tables later.
A
"jaylou" <jaylou@.discussions.microsoft.com> wrote in message
news:B8391A53-D820-4EF7-8BA8-751A341E0EED@.microsoft.com...
> Hi All,
> I have a bit of a delema here, that I know someone knows how to do it
> properly.
> If the value of DSP_IN_HOUSE = 1, I need the where clause to say:
> where DSP_IN_HOUSE_IN = F.CollectorDesc
> the code I am using is:
> left outer join tlkCollector F
> on case when DSP_IN_HOUSE = 1 then DSP_IN_HOUSE_IN = F.CollectorDesc
> when DSP_IN_HOUSE = 0 then DSP_RE_OPEN_IN = F.CollectorDesc
> end
> Is this possible without building the where clause dynamically?
> TIA,
> Joe
>|||You cannot use case statments like that. A case statement returns a value.
Honestly, when you run into problems like this in your query you know it is
time to reconsider your design :-)
John
"jaylou" wrote:

> Hi All,
> I have a bit of a delema here, that I know someone knows how to do it
> properly.
> If the value of DSP_IN_HOUSE = 1, I need the where clause to say:
> where DSP_IN_HOUSE_IN = F.CollectorDesc
> the code I am using is:
> left outer join tlkCollector F
> on case when DSP_IN_HOUSE = 1 then DSP_IN_HOUSE_IN = F.CollectorDesc
> when DSP_IN_HOUSE = 0 then DSP_RE_OPEN_IN = F.CollectorDesc
> end
> Is this possible without building the where clause dynamically?
> TIA,
> Joe
>|||Thank you for the help! I did know this but my brain went on vacation for
some reason. I guess I needed an extra pair of eyes look at what I thought
looked right. :)
I normally use aliases when I create SPs this is a one time converstion from
an Access Application into a .net App with a SQL Backend.
And YES I do curse them out all the time. this is part of my very large
project of cleaning up all tables and procedure here.
Aren't I a lucky one' :)
"Aaron Bertrand [SQL Server MVP]" wrote:

> CASE is an expression that returns a value; it is not a logic flow operato
r
> that allows you to change the meaning and semantics of a query. Assuming
> F.CollectorDesc, DSP_IN_HOUSE_IN and DSP_RE_OPEN_IN (curse the people who
> named your columns!) are the same data type:
>
> ON F.CollectorDesc = CASE DSP_IN_HOUSE
> WHEN 1 THEN DSP_IN_HOUSE_IN
> WHEN 0 THEN DSP_RE_OPEN_IN
> END
>
> By the way, you should really get in the habit of using aliases on all of
> the tables in your join/where clauses. Leaving them out just because
> they're the only table with such a column is confusing for other readers /
> maintainers of the code, and could bite you if such a column is added to o
ne
> of the tables later.
> A
>
> "jaylou" <jaylou@.discussions.microsoft.com> wrote in message
> news:B8391A53-D820-4EF7-8BA8-751A341E0EED@.microsoft.com...
>
>sql

Sunday, March 25, 2012

Case sensitive search

I use to apply varbinary clause to go for a case sensitive search.Suppose for the case
use pubs
SELECT * FROM EMPLOYEE WHERE
convert(varbinary,LNAME)=convert(varbinary,'Chang' )

I am getting the correct result in every way.

But when I apply the same rule in the following way
use northwind
SELECT * FROM employees WHERE
convert(varbinary,lastname)=convert(varbinary,'Kin g')

I am not getting any result wheather I pass the correct case sensetive parameter or not.

Can anybody help me why there is a difference in these two results?
One thing I like to mention in the first case the data type is varchar and in the latter case the datatype is nvarchar.Is this not applicable to the fields of type nvarchar.

Subhasishmaybe there's some blanks after LastName :
convert(varbinary,Rtim(LastName))=...|||Indeed nvarchar is the problem

convert(varbinary,lastname)=convert(varbinary,N'Ki ng')

try
SELECT lastname, convert(varbinary,lastname), convert(varbinary,'King')
FROM employees|||this will work for you :

Select * From employees
where
convert(varbinary,convert(varchar,lastname))=
convert(varbinary,'Buchanan')

converting the nvarchar in varchar and then into a varbinary

Case sensitive problem

You simply need to change the collation in the WHERE clause so that it is
case sensitive. The following example illustrates how the COLLATE clause ca
n
be used to define the collation:
CREATE TABLE [Function]
(
[Function] VARCHAR(100)
)
INSERT [Function] SELECT 'dr'
INSERT [Function] SELECT 'DR'
INSERT [Function] SELECT 'Dr'
SELECT *
FROM [Function]
WHERE [Function] = 'Dr'
Returns:
Function
dr
DR
Dr
(3 row(s) affected)
SELECT *
FROM [Function]
WHERE [Function] = 'Dr' COLLATE LATIN1_General_CS_AS
Function
Dr
(1 row(s) affected)
HTH
- Peter Ward
WARDY IT Solutions
"bad_boyu" wrote:

> Hello,
> I have a very.. very.. very big database that has a table with let's
> say column "Function". I want to do different selects on this column
> "Function". This select must be case sensitive, so if i do a select
> with like "Dr" then the results must contain the Function that have D
> in uppercase and r in lowercase. When the database was created there
> were no constraints concerning column "Function", concern like all
> fields are in uppercase.
> Is there a solution to do this selects(case sensitive) without changing
> the database?
> Thanks,
> BB
>To add on to Peter's response, you can also include the case-insensitive
predicate so that an index on the column can be used:
SELECT *
FROM [Function]
WHERE [Function] = 'Dr' AND
[Function] = 'Dr' COLLATE LATIN1_General_CS_AS
Hope this helps.
Dan Guzman
SQL Server MVP
"bad_boyu" <silaghi.ovidiu@.gmail.com> wrote in message
news:1150245243.474122.145330@.i40g2000cwc.googlegroups.com...
> Hello,
> I have a very.. very.. very big database that has a table with let's
> say column "Function". I want to do different selects on this column
> "Function". This select must be case sensitive, so if i do a select
> with like "Dr" then the results must contain the Function that have D
> in uppercase and r in lowercase. When the database was created there
> were no constraints concerning column "Function", concern like all
> fields are in uppercase.
> Is there a solution to do this selects(case sensitive) without changing
> the database?
> Thanks,
> BB
>|||Hello,
I have a very.. very.. very big database that has a table with let's
say column "Function". I want to do different selects on this column
"Function". This select must be case sensitive, so if i do a select
with like "Dr" then the results must contain the Function that have D
in uppercase and r in lowercase. When the database was created there
were no constraints concerning column "Function", concern like all
fields are in uppercase.
Is there a solution to do this selects(case sensitive) without changing
the database?
Thanks,
BB|||You simply need to change the collation in the WHERE clause so that it is
case sensitive. The following example illustrates how the COLLATE clause ca
n
be used to define the collation:
CREATE TABLE [Function]
(
[Function] VARCHAR(100)
)
INSERT [Function] SELECT 'dr'
INSERT [Function] SELECT 'DR'
INSERT [Function] SELECT 'Dr'
SELECT *
FROM [Function]
WHERE [Function] = 'Dr'
Returns:
Function
dr
DR
Dr
(3 row(s) affected)
SELECT *
FROM [Function]
WHERE [Function] = 'Dr' COLLATE LATIN1_General_CS_AS
Function
Dr
(1 row(s) affected)
HTH
- Peter Ward
WARDY IT Solutions
"bad_boyu" wrote:

> Hello,
> I have a very.. very.. very big database that has a table with let's
> say column "Function". I want to do different selects on this column
> "Function". This select must be case sensitive, so if i do a select
> with like "Dr" then the results must contain the Function that have D
> in uppercase and r in lowercase. When the database was created there
> were no constraints concerning column "Function", concern like all
> fields are in uppercase.
> Is there a solution to do this selects(case sensitive) without changing
> the database?
> Thanks,
> BB
>|||To add on to Peter's response, you can also include the case-insensitive
predicate so that an index on the column can be used:
SELECT *
FROM [Function]
WHERE [Function] = 'Dr' AND
[Function] = 'Dr' COLLATE LATIN1_General_CS_AS
Hope this helps.
Dan Guzman
SQL Server MVP
"bad_boyu" <silaghi.ovidiu@.gmail.com> wrote in message
news:1150245243.474122.145330@.i40g2000cwc.googlegroups.com...
> Hello,
> I have a very.. very.. very big database that has a table with let's
> say column "Function". I want to do different selects on this column
> "Function". This select must be case sensitive, so if i do a select
> with like "Dr" then the results must contain the Function that have D
> in uppercase and r in lowercase. When the database was created there
> were no constraints concerning column "Function", concern like all
> fields are in uppercase.
> Is there a solution to do this selects(case sensitive) without changing
> the database?
> Thanks,
> BB
>|||Thanks a lot for these replies!
But I have another problem, I need that the method LIKE or something
similar to be case-sensitive! The Function column has fields like this:
"Dr Bad Boy", "DR Angelina",
"Prof dr Italian", "Prof Dr Adrian",...
Is there any solution for this kind of problem?
Best regards,
BB
Dan Guzman wrote:
> To add on to Peter's response, you can also include the case-insensitive
> predicate so that an index on the column can be used:
> SELECT *
> FROM [Function]
> WHERE [Function] = 'Dr' AND
> [Function] = 'Dr' COLLATE LATIN1_General_CS_AS
> --
> Hope this helps.
> Dan Guzman
> SQL Server MVP|||See if this helps:
http://vyaskn.tripod.com/case_sensi..._sql_server.htm
--
HTH,
Vyas, MVP (SQL Server)
SQL Server Articles and Code Samples @. http://vyaskn.tripod.com/
"bad_boyu" <silaghi.ovidiu@.gmail.com> wrote in message
news:1150245243.474122.145330@.i40g2000cwc.googlegroups.com...
Hello,
I have a very.. very.. very big database that has a table with let's
say column "Function". I want to do different selects on this column
"Function". This select must be case sensitive, so if i do a select
with like "Dr" then the results must contain the Function that have D
in uppercase and r in lowercase. When the database was created there
were no constraints concerning column "Function", concern like all
fields are in uppercase.
Is there a solution to do this selects(case sensitive) without changing
the database?
Thanks,
BB|||On 14 Jun 2006 02:08:55 -0700, bad_boyu wrote:

>Thanks a lot for these replies!
>But I have another problem, I need that the method LIKE or something
>similar to be case-sensitive! The Function column has fields like this:
>"Dr Bad Boy", "DR Angelina",
>"Prof dr Italian", "Prof Dr Adrian",...
>Is there any solution for this kind of problem?
Hi BB,
SELECT *
FROM Function
WHERE Function LIKE '%Dr%' COLLATE LATIN1_General_CS_AS
Hugo Kornelis, SQL Server MVP|||Thanks for these quick replies!!! I believe it works ;)
You are the best!|||Thanks a lot for these replies!
But I have another problem, I need that the method LIKE or something
similar to be case-sensitive! The Function column has fields like this:
"Dr Bad Boy", "DR Angelina",
"Prof dr Italian", "Prof Dr Adrian",...
Is there any solution for this kind of problem?
Best regards,
BB
Dan Guzman wrote:
> To add on to Peter's response, you can also include the case-insensitive
> predicate so that an index on the column can be used:
> SELECT *
> FROM [Function]
> WHERE [Function] = 'Dr' AND
> [Function] = 'Dr' COLLATE LATIN1_General_CS_AS
> --
> Hope this helps.
> Dan Guzman
> SQL Server MVP

Tuesday, March 20, 2012

CASE in WHERE clause?

I would like to select customers from my database depending on some criteria that the users choose - such as area code, company size etc. Since i have about 15 criteria and the users want to be able to choose many criteria for one selection i can't make one procedure for each criteria - i would end up with about a hundred procedures. I want to let the users choose what criteria to search on and have ONE single select statement that return the customers. Something like:

select name, address, city etc
from customer
where if users want to see customers of a certain type then type = @.myInParameterForType
and if users want to see customers from a certain area then area = @.myInParameterForArea

is this possible? sorry if i made you all confused...my english is not perfect! Thanks in advance!Yes, you may use CASE in where|||one easy (but not very performant) way is to build your "where" clause in your application (ie:web form ) and send it to your sp:
------------------------
CREATE PROCEDURE mySP

(
@.WhereClause varchar(4000)
)

AS
Declare @.SQL varchar(6000)

begin

set @.SQL = 'SELECT field1, field2 ... from myTable where ' + @.WhereClause + ' ORDER BY someID'

end

EXEC (@.SQL)

RETURN

GO
------------------------

when you have many optional parameter it is very conveniant

CASE in where clause?

I want to create SQL (maybe stored proc) using a SELECT statement that can
add WHERE conditions if (and only if) values are sent to it. For example:
SELECT ID, Person
FROM People
WHERE LastName LIKE '%@.var1%' +
CASE WHEN @.var2 IS NOT NULL THEN ' AND TypeCode = ' + @.var2
ELSE ''
END
...etc
Is this possible? Thanks
David> SELECT ID, Person
> FROM People
> WHERE LastName LIKE '%@.var1%' +
> CASE WHEN @.var2 IS NOT NULL THEN ' AND TypeCode = ' + @.var2
> ELSE ''
> END
Did you mean:
SELECT ID, Person
FROM People
WHERE LastName LIKE '%' + @.var1 + '%'
AND TypeCode = COALESCE(@.TypeCode, TypeCode)
or more verbosely
SELECT ID, Person
FROM People
WHERE LastName LIKE '%' + @.var1 + '%'
AND TypeCode = CASE WHEN @.TypeCode IS NULL THEN TypeCode ELSE @.TypeCode END
CASE is an expression that returns a single value. It is *NOT* used for
flow control.|||could I suggest a slight amendment (and add a question):
SELECT ID, Person
FROM People
WHERE LastName LIKE '%' + @.var1 + '%'
AND (@.TypeCode is null OR TypeCode = @.TypeCode)
this way when @.typecode is null the lazy evaluation of SQL will mean it
won't even look at the second statement.
I've found if it's put the other way:
WHERE Typecode = @.TypeCode OR @.TypeCode is null
it will first evaluation Typecode = @.TypeCode, causing it to scan that
field, then it will evaluate the second statement.
I'm not sure but I suspect your suggestion of Typecode =
COALLESCE(@.TypeCode, TypeCode) will cause it to read the typecode field
even when a null value is passed to it.
Cheers
Will|||> I've found if it's put the other way:
> WHERE Typecode = @.TypeCode OR @.TypeCode is null
> it will first evaluation Typecode = @.TypeCode, causing it to scan that
> field, then it will evaluate the second statement.
There is no guarantee in the order of execution within a clause, it could go
left to right, it could go right to left.

> I'm not sure but I suspect your suggestion of Typecode =
> COALLESCE(@.TypeCode, TypeCode) will cause it to read the typecode field
> even when a null value is passed to it.
Really hard to say without table structure, sample data, row counts, and the
ability to actually test and examine query plans.|||"There is no guarantee in the order of execution within a clause, it
could go
left to right, it could go right to left. "
I know you're an MVP, and do indeed know SQL server way better than me,
but still I feel I have to ask - are you sure about this?
it's just that I've found on several occasions that if I switch the 2
statements around it changes the execution plan fundamentally, and
doesn't do any table scans (when the value is null of course). If the
order was not an issue then surely switching the order would not affect
the query?
Thanks
Will|||> it's just that I've found on several occasions that if I switch the 2
> statements around it changes the execution plan fundamentally, and
> doesn't do any table scans (when the value is null of course). If the
> order was not an issue then surely switching the order would not affect
> the query?
I didn't say order CAN'T be an issue. Just don't rely on this kind of
short-circuiting to work consistently.|||Fundamental mistake! There is no CASE **statement** in SQL. There is
a CASE **expression**; remember programming 101? Expressions return
scalar values, not control of execution flow.
SELECT person_id, person_name
FROM People
WHERE last_name LIKE '%' + @.var1 + '%'
AND foobar_code = COALESCE(@.my_code, foobar_code) ;
Even for an example, you had some pretty awful data element names.
Something can be a type of something or a code. It cannot be both.
There is no such thing as just an "id" -- it has to identify something
in particular.
You might want to get a book on SQL and data modeling.|||Will (william_pegg@.yahoo.co.uk) writes:
> could I suggest a slight amendment (and add a question):
> SELECT ID, Person
> FROM People
> WHERE LastName LIKE '%' + @.var1 + '%'
> AND (@.TypeCode is null OR TypeCode = @.TypeCode)
> this way when @.typecode is null the lazy evaluation of SQL will mean it
> won't even look at the second statement.
It's unclear here what you mean with "second statement".
@.TypeCode IS NULL OR TypeCode = @.TypeCode
would be the same as
TypeCode = @.TypeCode OR @.TypeCode IS NULL
when it comes to performance.
If you've seen something else, it might have been a mirage due to
caching.
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx|||My Apologies,
I really should stop questioning MVPs, you guys don't ever seem to be
wrong. I tried to recreate the situation and couldn't. My reasoning was
based on several queries I've debugged in the past that were displaying
a strange execution plan, and then by switching the statements around
(the "or" statements), increased performance dramatically (from 4s to
50ms). I assumed at the time that it was just a simple grammar case
that you could apply lazy evaluation, and that was how SQL was
optimising it, however it appears that there's more stuff going on.
perhaps the optimiser was having an odd day, or more likely there were
incorrect index statistics monkeying things up, but anyway, thanks for
clearing it up.
Cheers
Will|||The problem is that SQL is set-oriented and not sequential. The THEN
clauses in a CASE expression (which includes COALESCE()) all have to be
evaluated to determine the data type of the whole expression. It does
not matter if some of them are unreachable.
COALESCE correctly promotes its arguments to the highest data type in
the expression:
13 / COALESCE(CAST(NULL AS INTEGER), 2.00) = 6.5
The proprietary ISNULL() uses the first data type and gets things wrong
13 / ISNULL(CAST(NULL AS INTEGER), 2.00) = 6
You would need to write:
13 / ISNULL(CAST(NULL AS DECIMAL(4,2)), 2.00)sql

Case in Where Clause

Can you put a Case statement in a Where clause?
I have the following Cursor I am setting up that is giving me the error:
Server: Msg 170, Level 15, State 1, Line 26
Line 26: Incorrect syntax near '>'.
Declare @.SearchCursor Cursor
Set @.SearchCursor = Cursor for Select
CommandText,WhereClause,SearchID,UserID
from CandidateSearches where SearchAgent=1 and SearchAgentActive=1 and
(CASE WHEN NotifyFrequency = 'D' THEN
(DATEDIFF(DAY,SearchAgentLastRun,GetDate
()) > 0)
WHEN NotifyFrequency = 'W' THEN
(DATEDIFF(DAY,SearchAgentLastRun,GetDate
()) >= 7)
WHEN NotifyFrequency = 'M' THEN
(DATEDIFF(DAY,SEarchAgentLastRun,GetDate
()) >= 30) END)
Line 26 is the line the Case Statement is on.
What is the problem with this line?
Thanks,
TomHi Tom
The most important thing to keep in mind is that there is no case STATEMENT
in Transact-SQL. There is a case EXPRESSION, which can be used anywhere you
use an expression. So, you can use a case EXPRESSION in a WHERE, in place of
a value.
Without any more details like the DDL, or a description of what you're
trying to accomplish, my guess is that you want to compare
DATEDIFF(DAY,SearchAgentLastRun,GetDate(
)) to one of several different
values, depending on the value of NotifyFrequency. If that is a correct
understanding, you might try something like this in your WHERE clause:
where SearchAgent=1 and SearchAgentActive=1 and
DATEDIFF(DAY,SearchAgentLastRun,GetDate(
)) >= CASE NotifyFrequency
WHEN 'D' THEN 0
WHEN 'W' THEN 7
WHEN 'M' THEN 30
END
Also make sure to consider the case where NotifyFrequency is not one of (D,
W, M)
--
HTH
Kalen Delaney, SQL Server MVP
www.solidqualitylearning.com
"tshad" <tscheiderich@.ftsolutions.com> wrote in message
news:eeyXs5cMGHA.3960@.TK2MSFTNGP09.phx.gbl...
> Can you put a Case statement in a Where clause?
> I have the following Cursor I am setting up that is giving me the error:
> Server: Msg 170, Level 15, State 1, Line 26
> Line 26: Incorrect syntax near '>'.
> Declare @.SearchCursor Cursor
> Set @.SearchCursor = Cursor for Select
> CommandText,WhereClause,SearchID,UserID
> from CandidateSearches where SearchAgent=1 and SearchAgentActive=1 and
> (CASE WHEN NotifyFrequency = 'D' THEN
> (DATEDIFF(DAY,SearchAgentLastRun,GetDate
()) > 0)
> WHEN NotifyFrequency = 'W' THEN
> (DATEDIFF(DAY,SearchAgentLastRun,GetDate
()) >= 7)
> WHEN NotifyFrequency = 'M' THEN
> (DATEDIFF(DAY,SEarchAgentLastRun,GetDate
()) >= 30) END)
> Line 26 is the line the Case Statement is on.
> What is the problem with this line?
> Thanks,
> Tom
>|||"Kalen Delaney" <replies@.public_newsgroups.com> wrote in message
news:OQDXBGdMGHA.500@.TK2MSFTNGP15.phx.gbl...
> Hi Tom
> The most important thing to keep in mind is that there is no case
> STATEMENT in Transact-SQL. There is a case EXPRESSION, which can be used
> anywhere you use an expression. So, you can use a case EXPRESSION in a
> WHERE, in place of a value.
> Without any more details like the DDL, or a description of what you're
> trying to accomplish, my guess is that you want to compare
> DATEDIFF(DAY,SearchAgentLastRun,GetDate(
)) to one of several different
> values, depending on the value of NotifyFrequency. If that is a correct
> understanding, you might try something like this in your WHERE clause:
Exactly, but how would I do the instance where the case of 'D' is > 0 and
not >= 0?
Thanks,
Tom

> where SearchAgent=1 and SearchAgentActive=1 and
> DATEDIFF(DAY,SearchAgentLastRun,GetDate(
)) >= CASE NotifyFrequency
> WHEN 'D' THEN 0
> WHEN 'W' THEN 7
> WHEN 'M' THEN 30
> END
> Also make sure to consider the case where NotifyFrequency is not one of
> (D, W, M)
> --
> HTH
> Kalen Delaney, SQL Server MVP
> www.solidqualitylearning.com
>
> "tshad" <tscheiderich@.ftsolutions.com> wrote in message
> news:eeyXs5cMGHA.3960@.TK2MSFTNGP09.phx.gbl...
>
>|||I think what you are trying to do is this
Declare @.SearchCursor Cursor
Set @.SearchCursor = Cursor for Select
CommandText,WhereClause,SearchID,UserID
from CandidateSearches where SearchAgent=1 and
SearchAgentActive=1 and
((NotifyFrequency = 'D'
and DATEDIFF(DAY,SearchAgentLastRun,GetDate(
)) > 0) OR
(NotifyFrequency = 'W'
and DATEDIFF(DAY,SearchAgentLastRun,GetDate(
)) >= 7) OR
(NotifyFrequency = 'M'
and DATEDIFF(DAY,SearchAgentLastRun,GetDate(
)) >= 30))|||<markc600@.hotmail.com> wrote in message
news:1140022428.091421.209720@.g14g2000cwa.googlegroups.com...
>I think what you are trying to do is this
> Declare @.SearchCursor Cursor
> Set @.SearchCursor = Cursor for Select
> CommandText,WhereClause,SearchID,UserID
> from CandidateSearches where SearchAgent=1 and
> SearchAgentActive=1 and
> ((NotifyFrequency = 'D'
> and DATEDIFF(DAY,SearchAgentLastRun,GetDate(
)) > 0) OR
> (NotifyFrequency = 'W'
> and DATEDIFF(DAY,SearchAgentLastRun,GetDate(
)) >= 7) OR
> (NotifyFrequency = 'M'
> and DATEDIFF(DAY,SearchAgentLastRun,GetDate(
)) >= 30))
That was exactly what I ended up doing. I was just curious as to how to it
(if you can do it) using the Case statement.
Thanks,
Tom|||>> Declare @.SearchCursor Cursor
>That was exactly what I ended up doing. I was just curious as to how to it
>(if you can do it) using the Case statement.
You can do it using CASE, but it doesn't let you do anything that AND,
OR and () don't already let you do. Since it resolves to a values,
you have to use it to set a value that indicates success or failure,
then test that in a comparison.
SELECT CommandText, WhereClause, SearchID, UserID
FROM CandidateSearches
WHERE SearchAgent=1
AND SearchAgentActive=1
AND CASE
WHEN NotifyFrequency = 'D'
AND DATEDIFF(DAY,SearchAgentLastRun,GetDate(
)) > 0
THEN 1
WHEN NotifyFrequency = 'W'
AND DATEDIFF(DAY,SearchAgentLastRun,GetDate(
)) >= 7
THEN 1
WHEN NotifyFrequency = 'M'
AND DATEDIFF(DAY,SearchAgentLastRun,GetDate(
)) >= 30
THEN 1
ELSE 0
END = 1
Roy|||"Roy Harvey" <roy_harvey@.snet.net> wrote in message
news:31l7v1dnjf97n234q7ih23mnbq4rtti9u1@.
4ax.com...
> You can do it using CASE, but it doesn't let you do anything that AND,
> OR and () don't already let you do. Since it resolves to a values,
> you have to use it to set a value that indicates success or failure,
> then test that in a comparison.
> SELECT CommandText, WhereClause, SearchID, UserID
> FROM CandidateSearches
> WHERE SearchAgent=1
> AND SearchAgentActive=1
> AND CASE
> WHEN NotifyFrequency = 'D'
> AND DATEDIFF(DAY,SearchAgentLastRun,GetDate(
)) > 0
> THEN 1
> WHEN NotifyFrequency = 'W'
> AND DATEDIFF(DAY,SearchAgentLastRun,GetDate(
)) >= 7
> THEN 1
> WHEN NotifyFrequency = 'M'
> AND DATEDIFF(DAY,SearchAgentLastRun,GetDate(
)) >= 30
> THEN 1
> ELSE 0
> END = 1
>
I was as to what this did at first, but then I realized what it was
doing.
In the "OR" example, I would only get a record if one of the 3 tests (as
well as the SearchAgent and SearchAgentActive) were matched.
In your example, you are testing if the Case statement was "1". It was
clear when I put parens around the case statement. I thought at first you
were setting "End=1". But when I put the parans in, it made sense:
... AND (CASE
WHEN NotifyFrequency = 'D'
AND DATEDIFF(DAY,SearchAgentLastRun,GetDate(
)) > 0
THEN 1
WHEN NotifyFrequency = 'W'
AND DATEDIFF(DAY,SearchAgentLastRun,GetDate(
)) >= 7
THEN 1
WHEN NotifyFrequency = 'M'
AND DATEDIFF(DAY,SearchAgentLastRun,GetDate(
)) >= 30
THEN 1
ELSE 0
END) = 1
I think that is what is happening.
But as you said the OR does the same thing and is a little more clear and
you don't have to do the extra step of setting it to 0 or 1.
Thanks,
Tom
> Roy

CASE in a WHERE clause?

How can I do this?

Select somedata

From sometable

Where somecolumn = somevalue

and

CASE WHEN someparam = 1 THEN somecolumn2 <> somevalue2 ELSE somecolumn2 like '%'

Or this?

Select somedata

From sometable

Where somecolumn = somevalue

IF someparam = 1 AND somecolumn2 <> somevalue2

The error I am getting is Incorrect syntax near '<' using the first statement. Using the second statement I get an 'Error near IF' error or something like that.

Thanks for any help!

Hi !

As you see you can't do it that way, but you probably could use derived table syntax:

select dT.*, case when dt.newcol1>42 then '42t' else cast(dt.newcol2 as varchar(10)) end newcolX

from

( select t.*, case when t.col1='a' then 'A' else '' end newcol1,

case t.col2 when 2 then col3+col4 else col5 end newcol2

-- you can also use nested case...

from sometable t

) dt

where dt.newcol2 like 'text';

Best regards

Bjorn

P.S. there is no meaning in select-stmt, I'm just showing syntax...

|||

1.

Not sure this is the best way but you could generate your sql dynamically as a varchar then use EXEC to run the varchar

2.

Again, not sure this is correct but try:

.....WHERE (somecolumn = somevalue AND someparam = 1 AND somecolumn2 <> somevalue2)

OR

someparam <> 1

Perhaps even a union query could work for number 2

like I said they probably aren't 100% correct but hopefully point you in the right direction

|||hi,

i'm not sure what your requirements really are.. hope you can gets something from this example

declare @.ab varchar(100)

set @.ab = 1

select *
from (
select 'the quick' as a, 'brown fox' as b union all
select 'jumps over' as a, 'tha lazy dog' as b
) ab
where b = 'brown fox'
and a <> (case when @.ab = 1 then 'the quick' else '%' end)

set @.ab = 2

select *
from (
select 'the quick' as a, 'brown fox' as b union all
select 'jumps over' as a, 'tha lazy dog' as b
) ab
where b = 'brown fox'
and a <> (case when @.ab = 1 then 'the quick' else '%' end)

again, it really depends on the conditions that you need to evaluate|||

Use the following query..

Code Snippet

Select

somedata

From

sometable

Where

somecolumn = somevalue

And

(

(someparam = 1 And somecolumn2 <> somevalue2)

Or

(someparam <> 1 And somecolumn2 like '%')

)

|||

Thank you!!

|||

sarolabelle,

A "case" expression returns a value, so you need to compare the value returned by the "case" expression to something, in order to have a valid logic expression.

Select

somedata

From

sometable

Where

somecolumn = somevalue

and

CASE

WHEN someparam = 1 and somecolumn2 <> somevalue2 then 1

WHEN someparam != 1 and somecolumn2 like '%' then 1

else 0

end = 1

go

AMB

|||

Try this one

-- Case in Where

Code Snippet

Select * From EMP

Where (Country = 'India')

AND

(CASE

WHEN Salary < 5000 then 1

WHEN Age > 18 then 1

END = 1)

-- Case & where (individual)

Code Snippet

SELECT Name, Salary,

CASE

WHEN Salary < 5000 THEN 'No Tax'

WHEN Salary > 5000 THEN 'High Tax'

WHEN Salary = 5000 THEN 'Low Tax'

ELSE 'Invalid Data'

END

AS Tax

FROM EMP

WHERE country = 'USA'

for more details logon www.sqltree.com (under Conditional Processing folder)

Thanks

|||SQLTree -> It is not answering the question. Here the requirement is filtering the data.

Case in a Where clause

Hi all,
I have the following sql statement (it's ugly and it's not my work!!!).
UPDATE abo_tags SET locked = @.PrimaryGroupFilter, locking_user = @.user,
lockingdate = @.sDate
FROM abo_tags
INNER JOIN abo ON abo_tags.id_no_abo = abo.id_no
INNER JOIN products ON abo.id_no_product = products.id_no
LEFT OUTER JOIN abo_tags_subsidies ON abo_tags.id_no =
abo_tags_subsidies.id_no_abo_tag
WHERE abo_tags.id_no_invoice_type = 2 and abo_tags.locked in ('0', '',
NULL)
and abo_tags.validity_date >= @.mdatInvoiceFrom
and abo_tags.validity_date <= @.mdatInvoiceTo
and abo.id_no_primarygroup in (select primchild from invoicehelp where
parentkey = @.PrimaryGroupFilter)
and abo.id_no_product = case when @.mlngProduct >0 then @.mlngProduct else
abo.id_no_product end
and abo.id_no_school = case when @.mlngSchool > 0 then @.mlngSchool else
abo.id_no_school end
and abo_tags_subsidies.id_no_costrepresentative = case when @.mlngCostRep>0
then @.mlngCostRep else abo_tags_subsidies.id_no_costrepresentative end
I noticed that it takes a while to update records (over 20sec) on a table on
500K records. It looks like the problem lies in the CASE statements in the
WHERE clause. Is there a way to do it better than this?
Thanks,
IvanIvan,
Supposing that are int datatype, then try:
WHERE
abo_tags.id_no_invoice_type = 2 and abo_tags.locked in ('0', '')
and abo_tags.validity_date >= @.mdatInvoiceFrom
and abo_tags.validity_date <= @.mdatInvoiceTo
and abo.id_no_primarygroup in (
select primchild
from invoicehelp
where
parentkey = @.PrimaryGroupFilter)
and abo.id_no_product between coalesce(nullif(@.mlngProduct, 0), 1) and
coalesce(nullif(@.mlngProduct, 0), 2147483647)
and abo.id_no_school between coalesce(nullif(@.mlngSchool, 0), 1) and
coalesce(nullif(@.mlngSchool, 0), 2147483647)
and abo_tags_subsidies.id_no_costrepresentative between
coalesce(nullif(@.mlngCostRep, 0), 1) and coalesce(nullif(@.mlngCostRep, 0),
2147483647)
)
also, take off the null value from the list used with first IN operator.

> abo_tags.id_no_invoice_type = 2 and abo_tags.locked in ('0', '', null)
abo_tags.id_no_invoice_type = 2 and abo_tags.locked in ('0', '')
Dynamic Search Conditions in T-SQL
http://www.sommarskog.se/dyn-search.html
AMB
"Ivan Debono" wrote:

> Hi all,
> I have the following sql statement (it's ugly and it's not my work!!!).
> UPDATE abo_tags SET locked = @.PrimaryGroupFilter, locking_user = @.user,
> lockingdate = @.sDate
> FROM abo_tags
> INNER JOIN abo ON abo_tags.id_no_abo = abo.id_no
> INNER JOIN products ON abo.id_no_product = products.id_no
> LEFT OUTER JOIN abo_tags_subsidies ON abo_tags.id_no =
> abo_tags_subsidies.id_no_abo_tag
> WHERE abo_tags.id_no_invoice_type = 2 and abo_tags.locked in ('0', '',
> NULL)
> and abo_tags.validity_date >= @.mdatInvoiceFrom
> and abo_tags.validity_date <= @.mdatInvoiceTo
> and abo.id_no_primarygroup in (select primchild from invoicehelp where
> parentkey = @.PrimaryGroupFilter)
> and abo.id_no_product = case when @.mlngProduct >0 then @.mlngProduct else
> abo.id_no_product end
> and abo.id_no_school = case when @.mlngSchool > 0 then @.mlngSchool else
> abo.id_no_school end
> and abo_tags_subsidies.id_no_costrepresentative = case when @.mlngCostRep>
0
> then @.mlngCostRep else abo_tags_subsidies.id_no_costrepresentative end
> I noticed that it takes a while to update records (over 20sec) on a table
on
> 500K records. It looks like the problem lies in the CASE statements in the
> WHERE clause. Is there a way to do it better than this?
> Thanks,
> Ivan
>
>|||hi Ivan
This is the equivalent after removing the CASE in Where Clause:
UPDATE abo_tags
SET locked = @.PrimaryGroupFilter,
locking_user = @.user,
lockingdate = @.sDate
FROM abo_tags
INNER JOIN abo ON abo_tags.id_no_abo = abo.id_no
INNER JOIN products ON abo.id_no_product = products.id_no
LEFT OUTER JOIN abo_tags_subsidies ON abo_tags.id_no =
abo_tags_subsidies.id_no_abo_tag
WHERE
abo_tags.id_no_invoice_type = 2 and abo_tags.locked in ('0', '',NULL)
and abo_tags.validity_date >= @.mdatInvoiceFrom
and abo_tags.validity_date <= @.mdatInvoiceTo
and abo.id_no_primarygroup in (select primchild from invoicehelp where
parentkey = @.PrimaryGroupFilter)
and ((@.mlngProduct > 0 AND abo.id_no_product=@.mlngProduct) OR (@.mlngProduct
<= 0))
and ((@.mlngSchool > 0 AND abo.id_no_school=@.mlngSchool) OR (@.mlngSchool <= 0
))
and ((@.mlngCostRep > 0 AND abo_tags_subsidies.id_no_costrepresentative =
@.mlngCostRep) OR (@.mlngCostRep <= 0) )
I dont thin, there is a problem with the CASE. I believe its because of the
in (select primchild from invoicehelp where
parentkey = @.PrimaryGroupFilter)
please let me if this answers your question.
best Regards,
Chandra
http://chanduas.blogspot.com/
http://groups.msn.com/SQLResource/
---
"Ivan Debono" wrote:

> Hi all,
> I have the following sql statement (it's ugly and it's not my work!!!).
> UPDATE abo_tags SET locked = @.PrimaryGroupFilter, locking_user = @.user,
> lockingdate = @.sDate
> FROM abo_tags
> INNER JOIN abo ON abo_tags.id_no_abo = abo.id_no
> INNER JOIN products ON abo.id_no_product = products.id_no
> LEFT OUTER JOIN abo_tags_subsidies ON abo_tags.id_no =
> abo_tags_subsidies.id_no_abo_tag
> WHERE abo_tags.id_no_invoice_type = 2 and abo_tags.locked in ('0', '',
> NULL)
> and abo_tags.validity_date >= @.mdatInvoiceFrom
> and abo_tags.validity_date <= @.mdatInvoiceTo
> and abo.id_no_primarygroup in (select primchild from invoicehelp where
> parentkey = @.PrimaryGroupFilter)
> and abo.id_no_product = case when @.mlngProduct >0 then @.mlngProduct else
> abo.id_no_product end
> and abo.id_no_school = case when @.mlngSchool > 0 then @.mlngSchool else
> abo.id_no_school end
> and abo_tags_subsidies.id_no_costrepresentative = case when @.mlngCostRep>
0
> then @.mlngCostRep else abo_tags_subsidies.id_no_costrepresentative end
> I noticed that it takes a while to update records (over 20sec) on a table
on
> 500K records. It looks like the problem lies in the CASE statements in the
> WHERE clause. Is there a way to do it better than this?
> Thanks,
> Ivan
>
>|||Hi
Here is the query after removing the IN
UPDATE abo_tags
SET locked = @.PrimaryGroupFilter,
locking_user = @.user,
lockingdate = @.sDate
FROM abo_tags
INNER JOIN abo ON abo_tags.id_no_abo = abo.id_no
INNER JOIN products ON abo.id_no_product = products.id_no
INNER JOIN invoicehelp ON primchild = abo.id_no_primarygroup
LEFT OUTER JOIN abo_tags_subsidies ON abo_tags.id_no =
abo_tags_subsidies.id_no_abo_tag
WHERE
abo_tags.id_no_invoice_type = 2 and abo_tags.locked in ('0', '',NULL)
and abo_tags.validity_date >= @.mdatInvoiceFrom
and abo_tags.validity_date <= @.mdatInvoiceTo
and invoicehelp.parentkey = @.PrimaryGroupFilter
and ((@.mlngProduct > 0 AND abo.id_no_product=@.mlngProduct) OR (@.mlngProduct
<= 0))
and ((@.mlngSchool > 0 AND abo.id_no_school=@.mlngSchool) OR (@.mlngSchool <= 0
))
and ((@.mlngCostRep > 0 AND abo_tags_subsidies.id_no_costrepresentative =
@.mlngCostRep) OR (@.mlngCostRep <= 0) )
best Regards,
Chandra
http://chanduas.blogspot.com/
http://groups.msn.com/SQLResource/
---
"Chandra" wrote:
> hi Ivan
>
> This is the equivalent after removing the CASE in Where Clause:
> UPDATE abo_tags
> SET locked = @.PrimaryGroupFilter,
> locking_user = @.user,
> lockingdate = @.sDate
> FROM abo_tags
> INNER JOIN abo ON abo_tags.id_no_abo = abo.id_no
> INNER JOIN products ON abo.id_no_product = products.id_no
> LEFT OUTER JOIN abo_tags_subsidies ON abo_tags.id_no =
> abo_tags_subsidies.id_no_abo_tag
> WHERE
> abo_tags.id_no_invoice_type = 2 and abo_tags.locked in ('0', '',NULL)
> and abo_tags.validity_date >= @.mdatInvoiceFrom
> and abo_tags.validity_date <= @.mdatInvoiceTo
> and abo.id_no_primarygroup in (select primchild from invoicehelp where
> parentkey = @.PrimaryGroupFilter)
> and ((@.mlngProduct > 0 AND abo.id_no_product=@.mlngProduct) OR (@.mlngProduc
t
> <= 0))
> and ((@.mlngSchool > 0 AND abo.id_no_school=@.mlngSchool) OR (@.mlngSchool <=
0
> ))
> and ((@.mlngCostRep > 0 AND abo_tags_subsidies.id_no_costrepresentative =
> @.mlngCostRep) OR (@.mlngCostRep <= 0) )
> I dont thin, there is a problem with the CASE. I believe its because of th
e
> in (select primchild from invoicehelp where
> parentkey = @.PrimaryGroupFilter)
> please let me if this answers your question.
> best Regards,
> Chandra
> http://chanduas.blogspot.com/
> http://groups.msn.com/SQLResource/
> ---
>
> "Ivan Debono" wrote:
>|||Never heard about the Coalesce... need to read more about it.
Is there an alternative for the Subselect (select primchild...)'
Thanks,
Ivan
"Alejandro Mesa" <AlejandroMesa@.discussions.microsoft.com> schrieb im
Newsbeitrag news:7F407540-37EF-4341-946A-78FB74EB0E91@.microsoft.com...
> Ivan,
> Supposing that are int datatype, then try:
> WHERE
> abo_tags.id_no_invoice_type = 2 and abo_tags.locked in ('0', '')
> and abo_tags.validity_date >= @.mdatInvoiceFrom
> and abo_tags.validity_date <= @.mdatInvoiceTo
> and abo.id_no_primarygroup in (
> select primchild
> from invoicehelp
> where
> parentkey = @.PrimaryGroupFilter)
> and abo.id_no_product between coalesce(nullif(@.mlngProduct, 0), 1) and
> coalesce(nullif(@.mlngProduct, 0), 2147483647)
> and abo.id_no_school between coalesce(nullif(@.mlngSchool, 0), 1) and
> coalesce(nullif(@.mlngSchool, 0), 2147483647)
> and abo_tags_subsidies.id_no_costrepresentative between
> coalesce(nullif(@.mlngCostRep, 0), 1) and coalesce(nullif(@.mlngCostRep, 0),
> 2147483647)
> )
> also, take off the null value from the list used with first IN operator.
>
> abo_tags.id_no_invoice_type = 2 and abo_tags.locked in ('0', '')
>
> Dynamic Search Conditions in T-SQL
> http://www.sommarskog.se/dyn-search.html
>
> AMB
> "Ivan Debono" wrote:
>|||I would go thru the DDL and change the blank strings to '0', add a
DEFAULT and a check constraint to prevent this problem in the future.

CASE Help

I am trying to put a case statement into my Having Clause or Where Clause. Both come up with the same error "Error near '='" in the THEN statement. I'm not sure why this is not working. The idea of this statement is to look at the date and if it is the first of the month it will return last months data, if not it gives me this months data.
If someone could give me and idea as to why this doesn't work or another solution that would be great. Thanks

SELECT TOP 100 PERCENT database.Point_time
FROM database
WHERE CASE WHEN datepart(dd, getdate())=1
THEN(MONTH(database.Point_time) = MONTH(getdate())-1) AND
(YEAR(database.Point_time) = YEAR(getdate()))
ELSE (MONTH(database.Point_time) = MONTH(getdate())) AND
(YEAR(database.Point_time) = YEAR(getdate()))
END
GROUP BY database.Point_time
ORDER BY database.Point_time.SELECT TOP 100 PERCENT
CASE
WHEN datepart(dd, getdate()) = 1 THEN MONTH(databasex.Point_time)-1
ELSE MONTH(databasex.Point_time)
END, (YEAR(databasex.Point_time))

FROM databasex

GROUP BY databasex.Point_time
ORDER BY databasex.Point_time|||That didn't work. It gave me one column with 1 thru 6 multiple times and a second column of just 2006.

This problem has to do with the statement in the THEN part of the CASE statement. SQL doesn't like the = sign. If there is a way to do it without the = sign I think that would work, but don't know how...|||well you can't put the case statment in the WHERE clause - it has to go in the SELECT stmnt, so this way may give you what you want.

if datepart(dd, getdate()) = 1
select TOP 100 PERCENT databasex.Point_time where MONTH(databasex.Point_time) = MONTH(getdate())-1
and YEAR(databasex.Point_time) = YEAR(getdate())
GROUP BY databasex.Point_time
ORDER BY databasex.Point_time

else
select TOP 100 PERCENT databasex.Point_time where MONTH(databasex.Point_time) = MONTH(getdate())
and YEAR(databasex.Point_time) = YEAR(getdate())
GROUP BY databasex.Point_time
ORDER BY databasex.Point_time|||That is infact wrong!

you can put a case statement in the where clause

SELECT TOP 100 PERCENT database.Point_time
FROM database
WHERE database.Point_time =

CASE WHEN datepart(dd, getdate())=1
THEN(MONTH(getdate())-1) AND
(YEAR(getdate()))

CASE ELSE (MONTH(getdate())) AND
(YEAR(getdate()))
END
GROUP BY database.Point_time
ORDER BY database.Point_time|||Sorry I made a mistake by accident in the previouse reply, always check your work. This is the correct way
SELECT TOP 100 PERCENT database.Point_time
FROM database
WHERE database.Point_time =

CASE
WHEN datepart(dd, getdate())=1
THEN(MONTH(getdate())-1) AND
(YEAR(getdate()))
WHEN (MONTH(getdate())) AND
(YEAR(getdate()))
END

GROUP BY database.Point_time
ORDER BY database.Point_time

Case function in T-SQL

Wondering if possible to use case function in where clause of T-SQL statement. I have this application that needs to get the recordsets based on the day of the date selected that is @.dDay in one of these set of values {0,7,14,21, more). Though, I know that if I use either of this:

datediff(dd,@.startdate,@.today) = @.dDay

or convert(varchar(12), @.startDate, 101) between convert(varchar(12), @.today, 101) and convert(varchar(12), dateadd(dd,@.dDay, @.today), 101)

It will work for only the values that are specific as in number but what of if "more" is selected which means that from that day upward, can i use this T-SQL to accomplish this. PLease help

Any suggestion is welcome. thanks

I think I got confused.. can you explain a bit more..?

|||

i too am confused by what you want but just keep in mind that if you include a function your where clause you will likely disallow the use of indexes on your date field, if there is one

|||

 
SELECT *FROM tblWHERE StartDate>=DATEADD(DAY,DATEDIFF(DAY, 0, @.today), 0)AND StartDate<CASEWHEN @.dday='more'THEN'9999-12-31'ELSEDATEADD(DAY,DATEDIFF(DAY, 0, @.today), @.dday+1)END

|||

I mean this; I have a textbox with a dropdownlist control to search my databasein which the user can select either "Today", "7 days", "14 days", and "More". If a user select either of the list item except "More", i think i can easily use the"between" and"and" to get the recordsets or usedatediff function to get the recordsets, but what of if the user select"more" which is not bounded but means "from that day and on", how can one control this by using the same T-SQL statement to return the recordset from the database. I am not ad-hoc method to access my datastore but stored procedure.

So i am looking at usingcase function to make the decision and return the recordsets. Is it possible or is there any simpler way?.

Please Help. Urgent

|||

If I understand you correctly, I would use a second stored procedure for the "More" case. IOW,

select @.SomeDate = datediff(....)

then

select ...... from..... where DateField < @.SomeDate

If the user selects a specific number of days, select proc1, else select proc2

Another option is to use a big if statement with 2 selects (to handle either case), but that won't optimize as well

|||

If that in the case, I would change the listitem in the dropdown with the "more" text to have an extremely large value, like say 100000 (250ish years). Then you don't have to have anything complicated on the SQL side. That way you can still have "more" displayed in the listbox, but when it actually goes to send it to the SqlDatasource, it will send 100000 instead of the word more.

Case Expression within a Stored Proc

Is it possible? I have a request to create a stored proc that will
dynamically add a range to a WHERE clause based on a numeric value of a
comment type. If the incoming comment type request is say 10, the
where clause needs to be set to IN(10,11,12,13,14,15,16,17,18,19)OR if
a 20 is passed in the clause would read IN(20,21....)
So I was thinking that a CASE expression within the proc would be the
best way to go, but have had no luck in finding an example or any other
related information regarding CASE exp in a proc.
TIA
BillOn 8 Sep 2004 06:44:18 -0700, Bill Willyerd wrote:

>Is it possible? I have a request to create a stored proc that will
>dynamically add a range to a WHERE clause based on a numeric value of a
>comment type. If the incoming comment type request is say 10, the
>where clause needs to be set to IN(10,11,12,13,14,15,16,17,18,19)OR if
>a 20 is passed in the clause would read IN(20,21....)
>So I was thinking that a CASE expression within the proc would be the
>best way to go, but have had no luck in finding an example or any other
>related information regarding CASE exp in a proc.
>TIA
>Bill

Hi Bill,

In this case (no pun intended), I'd simply write it like this:

WHERE MyColumn BETWEEN @.parameter AND @.parameter + 9

Best, Hugo
--

(Remove _NO_ and _SPAM_ to get my e-mail address)|||On 8 Sep 2004 08:17:57 -0700, Bill Willyerd wrote:

>Sorry I didn't add that if a request for specfic comment type comes in
>like 22 we only return the type 22's.
>I do like the BETWEEN stmt though I haven't seen that before, I will
>remember that one.
>Thx, Bill

Hi Bill,

Is the request for "a specific comment type" passed in through a seperate
parameter? And the other parameter is used to get a range of comment
types?

CREATE PROC MyProc @.Specific int,
@.RangeStart int
AS
IF (@.Specific IS NULL AND @.RangeStart IS NULL)
OR (@.Specific IS NOT NULL AND @.RangeStart IS NOT NULL)
RAISERROR ('Supply exactly one of the two parameters', 16, 1)
ELSE
IF @.Specific IS NOT NULL
SELECT Column List
FROM YourTable
WHERE MyColumn = @.Specific
ELSE
SELECT Column List
FROM YourTable
WHERE MyColumn BETWEE @.RangeStart AND @.RangeStart + 9
go
(untested)

Best, Hugo
--

(Remove _NO_ and _SPAM_ to get my e-mail address)|||On 8 Sep 2004 16:28:26 -0700, Bill Willyerd wrote:

>At present it comes as a single request.
(snip)

Hi Bill,

How do you know if the request is for a specific comment type or for a
range? Surely, there has to be some way to distinguish a request for
comment type '20' (meaning just 20) from a request for comment type '20'
(meaning all values 20 through 29).

Maybe this is a good time to explain what information should be included
in newsgroup postings to maximise the chance to get a useful reply:

* Table structure, posted as DDL (CREATE TABLE statements, omitting
irrelevant columns but including all constraints);
* Sample data, posted as INSERT statements (and please verify that the
CREATE TABLE and INSERT statements you post work properly in an empty test
database!);
* Expected output, based on sample data;
* The SQL code you already got (if any), plus the results these give you
and the reason why that is wrong. If you get an error message, copy and
paste the full message;
* A short, concise description of the business problem you're trying to
solve.

Check out these sites as well:
http://www.aspfaq.com/etiquette.asp?id=5006
http://vyaskn.tripod.com/code.htm#inserts

Best, Hugo
--

(Remove _NO_ and _SPAM_ to get my e-mail address)

case expression in where clause and null's

Using SQL Server 2005
I have a simple table example with two columns: FirstName varchar(20) and
LastName varchar(20)
I am doing something like this in a stored procedure where @.firstname and
@.lastname are passed in and @.lastname could be null
select * from table where FirstName = @.firstname and LastName =
COALESCE(@.LastName, LastName)
I am also using "set ansi_nulls off".
The query should give names where LastName is null if @.Lastname = null but
that's not happening. Why?
John DalbergBecause COALESCE returns the first non-NULL value. If @.LastName is null,
then it won't return @.LastName, it will Return LastName (the column, not the
variable).
Essentially making your stmt:
select * from table where FirstName = @.firstname and LastName = LastName
or rather
select * from table where FirstName = @.firstname
"John Dalberg" <nospam@.nospam.sss> wrote in message
news:20060405191639.387$oV@.newsreader.com...
> Using SQL Server 2005
> I have a simple table example with two columns: FirstName varchar(20) and
> LastName varchar(20)
> I am doing something like this in a stored procedure where @.firstname and
> @.lastname are passed in and @.lastname could be null
> select * from table where FirstName = @.firstname and LastName =
> COALESCE(@.LastName, LastName)
> I am also using "set ansi_nulls off".
> The query should give names where LastName is null if @.Lastname = null but
> that's not happening. Why?
> John Dalberg|||>The query should give names where LastName is null if @.Lastname = null but
>that's not happening. Why?
It sounds like this might be confusion over how NULL works.
If table.LastName IS NULL, and @.LastName IS NULL, then
COALESCE(@.LastName, LastName) will resolve to NULL. In that situation
the test:
LastName = COALESCE(@.LastName, LastName)
resolves to:
NULL = NULL
Which comparison will never resolve to TRUE. NULL is never equal to
anything, including another NULL. Consider these comparisons:
NULL = 'banana'
NULL <> 'banana'
NULL = NULL
NULL <> NULL
None of those can ever be resolved as TRUE, because equality (or
inequality) can only result from comparing something to something.
NULL is nothing, and can not be compared at all.
Roy Harvey
Beacon Falls, CT
On 05 Apr 2006 23:06:02 GMT, nospam@.nospam.sss (John Dalberg) wrote:

>Using SQL Server 2005
>I have a simple table example with two columns: FirstName varchar(20) and
>LastName varchar(20)
>I am doing something like this in a stored procedure where @.firstname and
>@.lastname are passed in and @.lastname could be null
>select * from table where FirstName = @.firstname and LastName =
>COALESCE(@.LastName, LastName)
>I am also using "set ansi_nulls off".
>The query should give names where LastName is null if @.Lastname = null but
>that's not happening. Why?
>John Dalberg|||Roy Harvey <roy_harvey@.snet.net> wrote:
> It sounds like this might be confusion over how NULL works.
> If table.LastName IS NULL, and @.LastName IS NULL, then
> COALESCE(@.LastName, LastName) will resolve to NULL. In that situation
> the test:
> LastName = COALESCE(@.LastName, LastName)
> resolves to:
> NULL = NULL
> Which comparison will never resolve to TRUE. NULL is never equal to
> anything, including another NULL. Consider these comparisons:
> NULL = 'banana'
> NULL <> 'banana'
> NULL = NULL
> NULL <> NULL
> None of those can ever be resolved as TRUE, because equality (or
> inequality) can only result from comparing something to something.
> NULL is nothing, and can not be compared at all.
But when you have set ansi_nulls off and run:
select * from table where lastname = null, it returns rows where lastname=
null
Doesn't that statement translate to:
select * from table where null = null ?
and when you set ansi_nulls on
one needs to write it as: select * from table where lastname is null ?
John Dalberg|||take a look at this
declare @.v1 int,@.v2 int
select @.v1 = null,@.v2 = null
if @.v1 =@.v2
print 'equal'
else
print 'not equal'
go
declare @.v1 int,@.v2 int
select @.v1 = null,@.v2 = null
if @.v1 is null and @.v2 is null
print 'Both null'
else
print 'both not null'
go
set ansi_nulls off
go
declare @.v1 int,@.v2 int
select @.v1 = null,@.v2 = null
if @.v1 =@.v2
print 'equal'
else
print 'not equal'
go
set ansi_nulls on
go
Denis the SQL Menace
http://sqlservercode.blogspot.com/|||"Paul Wehland" <PaulWe@.REMOVE-ME.Avanade.com> wrote:
> Because COALESCE returns the first non-NULL value. If @.LastName is null,
> then it won't return @.LastName, it will Return LastName (the column, not
> the variable).
> Essentially making your stmt:
> select * from table where FirstName = @.firstname and LastName =
> LastName or rather
> select * from table where FirstName = @.firstname
What does COALESCE return in this case when there's no none null values?
(not that it makes sense)
select * from table where FirstName = @.firstname and LastName =
COALESCE(@.LastName, @.LastName)
Would that translate to:
select * from table where FirstName = @.firstname and LastName = null ?
Doesn't 'set ansi_null off' make 'null =null' evaluate to true?
Anyways, I need the where clause to include the lastname if @.lastname has a
value and return null lastnames rows if @.lastname is null. I couldn't find
a way to do it in a CASE expression. I can do it in a dynamic sql.
John Dalberg
> "John Dalberg" <nospam@.nospam.sss> wrote in message
> news:20060405191639.387$oV@.newsreader.com...|||>>What does COALESCE return in this case when there's no none null values?
(not that it makes sense)
COALESCE will return the first non NULL value
Here is an example
declare @.v1 int,@.v2 int,@.v3 int,@.v4 int
select @.v1 = null,@.v2 = null,@.v3 =4,@.v4 =8
select coalesce(@.v1,@.v2,@.v3,@.v4)
Denis the SQL Menace
http://sqlservercode.blogspot.com/|||"SQL" <denis.gobo@.gmail.com> wrote:
> take a look at this
> declare @.v1 int,@.v2 int
> select @.v1 = null,@.v2 = null
> if @.v1 =@.v2
> print 'equal'
> else
> print 'not equal'
> go
> declare @.v1 int,@.v2 int
> select @.v1 = null,@.v2 = null
> if @.v1 is null and @.v2 is null
> print 'Both null'
> else
> print 'both not null'
> go
> set ansi_nulls off
> go
> declare @.v1 int,@.v2 int
> select @.v1 = null,@.v2 = null
> if @.v1 =@.v2
> print 'equal'
> else
> print 'not equal'
> go
> set ansi_nulls on
> go
I understand the principles. That's why I included set ansi_nulls off in my
clarification.|||It is easier to communicate using DDL. I've added DDL at the end of this tex
t so we can use that
from here on.
Let me see if I can re-phrase your question:
You have some rows which has NULL on the lastname column. You want to find t
hem using ANSI_NULLS OFF
and by passing in NULL in the @.lastname parameter of your stored procedure.
So, in the query, you
have the following condition:
AND LastName = COALESCE(@.LastName, LastName)
So, if if you pass NULL for the @.lastname parameter, the condition will tran
slate to:
AND LastName = LastName
And you wonder why that will not return the rows where you have NULL in the
lastname column. Is that
correct?
If so, read in Books Online about SET ANSI_NULLS OFF. It only comments about
comparsions between a
column and NULL, not between two columns where each has NULL. I guess that t
his is how Sybase
defined it some 20 years ago, and MS has kapt this behavior. You could do a
BOL feedback and ask
them to clarify this in the 2005 BOL.
DDL:
USE tempdb
CREATE TABLE t(firstname varchar(30) not null, lastname varchar(30) null)
insert into t (firstname, lastname)
VALUES('John', 'Dalberg')
insert into t (firstname, lastname)
VALUES('Franz', NULL)
SET ANSI_NULLS OFF
GO
CREATE PROC p
@.firstname varchar(30), @.lastname varchar(30)
AS
SELECT firstname, lastname
from t
where FirstName = @.firstname
AND LastName = COALESCE(@.LastName, LastName)
GO
EXEC p 'John', 'Dalberg'
EXEC p 'John', NULL
EXEC p 'Franz', NULL
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
Blog: http://solidqualitylearning.com/blogs/tibor/
"John Dalberg" <nospam@.nospam.sss> wrote in message news:20060406121819.765$iB@.newsreader.c
om...
> Roy Harvey <roy_harvey@.snet.net> wrote:
> But when you have set ansi_nulls off and run:
> select * from table where lastname = null, it returns rows where lastname=
> null
> Doesn't that statement translate to:
> select * from table where null = null ?
> and when you set ansi_nulls on
> one needs to write it as: select * from table where lastname is null ?
> John Dalberg|||"Paul Wehland" <PaulWe@.REMOVE-ME.Avanade.com> wrote:
> Because COALESCE returns the first non-NULL value. If @.LastName is null,
> then it won't return @.LastName, it will Return LastName (the column, not
> the variable).
> Essentially making your stmt:
> select * from table where FirstName = ffirstname and LastName =
> LastName or rather
Right and that's the way it should work so when you have ansi_nulls off,
lastname = lastname will return rows where lastname is null and it will not
return these rows if set ansi_nulls on. I am missing what was wrong in my
statement.
so:
set ansi_nulls off;select * from table where FirstName = firstname and
LastName =lastname
&
select * from table
both return the same # of rows regardless whether lastname is null or not.
John Dalbergsql