473,378 Members | 1,605 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,378 software developers and data experts.

IF SELECT UNION

Using SQL 2000...

tblCustomer:
CustomerID int
CompanyName varchar(20)
HasRetailStores bit
HasWholesaleStores bit
HasOtherStores bit

tblInvoiceMessages:
MessageID int
MessageText varchar(100)
CustomerID int
AllRetailStores bit
AllWholesaleStores bit
AllOtherStores bit
AllStores bit
IsActive bit

The Invoice Messages are text blocks which will be added to invoices
going out to customers. A customer can have Retail stores, Wholesale
stores, and/or Other Stores. The messages can go to only those
customers with a specific type of store, or all customers, or to a
specific customer. It is important to note that a customer can have 1,
2 or all 3 types of stores. Here are a couple of sample entries in the
invoice messages table:

tblInovoiceMessages
1,For Customers with Retail and Wholesale Stores,0,1,1,0,0
2,Only For Customer # 10,10,0,0,0,0
....

Attempt #1 (IF SELECT UNION SELECT)
IF (SELECT TC.HasRetailDestinations
FROM tblCustomer TC
WHERE TC.CustomerID = @CustomerID) = 1
SELECT *
FROM tblInvoiceMessages IM
WHERE (IM.IsActive = 1) AND (IM.AllRetailStores = 1)
UNION
SELECT *
FROM tblInvoiceMessages IM
WHERE (IM.IsActive = 1) AND (IM.CustomerID = @CustomerID)

Attempt #1 checks if the Customer has retail stores, and if it does,
returns all messages for Retail Stores. The second Select statement
checks for all messages designated for that particular Customer. I use
Union to combine the tables (which have identical structures) and it
works great.

Attempt #2 (IF SELECT UNION SELECT UNION IF SELECT)
IF (SELECT TC.HasRetailStores
FROM tblCustomer TC
WHERE TC.CustomerID = @CustomerID) = 1
SELECT *
FROM tblInvoiceMessages IM
WHERE (IM.IsActive = 1) AND (IM.AllRetailStores = 1)
UNION
SELECT *
FROM tblInvoiceMessages IM
WHERE (IM.IsActive = 1) AND (IM.CustomerID = @CustomerID)
UNION
IF (SELECT TC.HasWholesaleStores
FROM tblCustomer TC
WHERE TC.CustomerID = @CustomerID) = 1
SELECT *
FROM tblInvoiceMessages IM
WHERE (IM.IsActive = 1) AND (IM.AllWholesaleStores = 1)

Attempt #2 is the same as Attempt#1 except that I attempt to Union
another If Select query to the first two queries. This attempt
generates:
Server: Msg 156, Level 15, State 1, Line 12
Incorrect syntax near the keyword 'IF'.

I have tested each individual If Select statement, and they all return
proper results. However, anytime I attempt to Union more than 1 If
Select statement together, I get the Msg 156 error. Is there some
limitation that I am not aware of?

Jul 23 '05 #1
4 6908
On 30 May 2005 13:29:24 -0700, Elroyskimms wrote:

(snip)
Attempt #2 is the same as Attempt#1 except that I attempt to Union
another If Select query to the first two queries. This attempt
generates:
Server: Msg 156, Level 15, State 1, Line 12
Incorrect syntax near the keyword 'IF'.

I have tested each individual If Select statement, and they all return
proper results. However, anytime I attempt to Union more than 1 If
Select statement together, I get the Msg 156 error. Is there some
limitation that I am not aware of?


Hi Elroyskimms,

UNION is part of a query. You can UNION together several SELECT clauses,
but you can't use control-flow code in between.

I think that you could get the output you need from the following query:

SELECT column list -- never use SELECT * in production code!!
FROM Customer AS c,
InvoiceMessages AS im
WHERE c.CustomerID = @CustomerID
AND im.IsActive = 1
AND ( im.CustomerID = @CustomerID
OR (im.AllRetailStores = 1 AND c.HasRetailStores = 1)
OR (im.AllWholeSaleStores = 1 AND c.HasWholeSaleStores = 1))

(untested, since you didn't post CREATE TABLE and INSERT statements with
test data and expected output - see www.asp.faq.com/5006)

Best, Hugo
--

(Remove _NO_ and _SPAM_ to get my e-mail address)
Jul 23 '05 #2
Elroyskimms (el*********@yahoo.com) writes:
Attempt #2 (IF SELECT UNION SELECT UNION IF SELECT)
IF (SELECT TC.HasRetailStores
FROM tblCustomer TC
WHERE TC.CustomerID = @CustomerID) = 1
SELECT *
FROM tblInvoiceMessages IM
WHERE (IM.IsActive = 1) AND (IM.AllRetailStores = 1)
UNION
SELECT *
FROM tblInvoiceMessages IM
WHERE (IM.IsActive = 1) AND (IM.CustomerID = @CustomerID)
UNION
IF (SELECT TC.HasWholesaleStores
FROM tblCustomer TC
WHERE TC.CustomerID = @CustomerID) = 1
SELECT *
FROM tblInvoiceMessages IM
WHERE (IM.IsActive = 1) AND (IM.AllWholesaleStores = 1)

Attempt #2 is the same as Attempt#1 except that I attempt to Union
another If Select query to the first two queries. This attempt
generates:
Server: Msg 156, Level 15, State 1, Line 12
Incorrect syntax near the keyword 'IF'.

I have tested each individual If Select statement, and they all return
proper results. However, anytime I attempt to Union more than 1 If
Select statement together, I get the Msg 156 error. Is there some
limitation that I am not aware of?


You have mixed up control-of-flow language with SELECT statememts.
This may best be explained by looking at the first batch, but reformatted:

IF (SELECT TC.HasRetailDestinations
FROM tblCustomer TC
WHERE TC.CustomerID = @CustomerID) = 1
BEGIN
SELECT *
FROM tblInvoiceMessages IM
WHERE (IM.IsActive = 1) AND (IM.AllRetailStores = 1)
UNION
SELECT *
FROM tblInvoiceMessages IM
WHERE (IM.IsActive = 1) AND (IM.CustomerID = @CustomerID)
END

IF is one statemet, SELECT is another. So you get a syntax error when
you try to use IF in the middle of a SELECT statement.

This might work for your second query:

IF (SELECT TC.HasRetailStores
FROM tblCustomer TC
WHERE TC.CustomerID = @CustomerID) = 1
BEGIN
SELECT *
FROM tblInvoiceMessages IM
WHERE (IM.IsActive = 1) AND (IM.AllRetailStores = 1)
UNION
SELECT *
FROM tblInvoiceMessages IM
WHERE (IM.IsActive = 1) AND (IM.CustomerID = @CustomerID)
UNION
SELECT *
FROM tblInvoiceMessages IM
WHERE (IM.IsActive = 1) AND (IM.AllWholesaleStores = 1)
AND EXISTS (SELECT
FROM tblCustomer TC
WHERE TC.CustomerID = @CustomerID
AND TC.HasWholesaleStores = 1)
END
--
Erland Sommarskog, SQL Server MVP, es****@sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 23 '05 #3
Thanks everyone for your help. I had incorrectly assumed that because
the result of the IF SELECT statement was in table form, I could use it
inside a SELECT statement like a nested SELECT. I modified Hugo's
suggestions just slightly and it seems to work great, and it is much
simpler then what I had originally planned.

Is there a security risk behind using SELECT * or is it a "Best
Practice"? Thanks!

-E

Jul 23 '05 #4
Elroyskimms (el*********@yahoo.com) writes:
Is there a security risk behind using SELECT * or is it a "Best
Practice"? Thanks!


Best practice.

Assume that the function where you use this query actually reads six of ten
columns. First of all you save some network bandwidth, by only getting
the columns you need. Second, assume that the DBA considers dropping
one of the columns. If you explicitly list the columns you need, he can
easily see whether you are using that column or not. Third, the DBA may add
another column, and insert it in the middle, if you now have referred to
columns by number in the client (which is bad practice), your function will
stop working.

SELECT * is wonderful for debugging when do you ad-hoc queries, but it's
bad in production code.
--
Erland Sommarskog, SQL Server MVP, es****@sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 23 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Chris Becker | last post by:
I have the following query: SELECT Month, Sum(Hits) AS Hits FROM tblHits GROUP BY Month ORDER BY Month Unfortunately it only returns rows for months that have data assigned to them. How...
17
by: kalamos | last post by:
This statement fails update ded_temp a set a.balance = (select sum(b.ln_amt) from ded_temp b where a.cust_no = b.cust_no and a.ded_type_cd = b.ded_type_cd and a.chk_no = b.chk_no group by...
1
by: jtwright | last post by:
I've got a view that creates a parent child relationship, this view is used in Analysis Services to create a dimension in a datastore. This query tends to deadlock after about 10 days of running...
3
by: dumbledad | last post by:
Hi All, I'm confused by how to replace a SELECT statement in a SQL statement with a specific value. The table I'm working on is a list of words (a column called "word") with an index int...
3
by: Ker | last post by:
I have a query that works great. It gives me the min for multiple fields. Within this query, I also need to get the max of some fields too. I currently have output of Date Name ...
3
by: Randall Skelton | last post by:
I have a number of tables with the general structure: Column | Type | Modifiers -----------+--------------------------+----------- timestamp | timestamp with time zone |...
6
by: Apaxe | last post by:
In the database i have a table with this information: key_id =1 key_desc =43+34+22+12 I want sum the values in key_desc. Something like: SELECT key_desc FROM table But the result of...
2
by: rickcf | last post by:
I have two tables. Table A is the main table I need to update and table B is the update table with the new data. Table B contains only two fields- fielda (also contained in table A for the linking...
4
by: Manikrag | last post by:
Hi Team, Is it possible to sort select query based on input string? I am looking for somthing like: select TOP 20 PREFERRED_NAME from FRS_TABLE where Lower(PREFERRED_NAME) like...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.