Friday, March 23, 2012

Help on filtering data

Why is
Select * from [Merchandise] where [Product Name] like '[ABCD]%'
the same as
Select * from [Merchandise] where [Product Name] between 'A' and 'D'
I can run
Select * from [Merchandise] where [Product Name] like 'A%'
and get Products that start with the letter "A" but they don't show up when I try to get all "A","B","C","D" Products.I would be surprised if this

Select * from [Merchandise] where [Product Name] like '[ABCD]%'

returns the same data as

Select * from [Merchandise] where [Product Name] between 'A' and 'D'

A product called "doughnut" would be returned by the first but not the second since 'doughnut' is considered greater than 'D'.

The first statement uses the wildcard brackets [] which will return all data starting with characters within the brackets. It can also be expressed as [A-D]%.

What's the issue?|||ricrecar you are right. I wrote this code

/****** Object: Table [dbo].[Merchandise] Script Date: 11/10/2004 9:18:41 AM ******/
CREATE TABLE [Merchandise] (
[Key Code] [int] NOT NULL ,
[Product Name] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Scientific Name] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Retail Price] [money] NULL ,
[Product Category] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
) ON [PRIMARY]
GO
INSERT [Merchandise] VALUES (5010,'Ageratum','Ageratum houstonianum',1.25,'Annuals')
INSERT [Merchandise] VALUES (5900,'Aster Opus',NULL,2.00,'Annuals')
INSERT [Merchandise] VALUES (5910,'Bachelor Button','Centaurea cyanus',2.00,'Annuals')
INSERT [Merchandise] VALUES (55515,'Bald Cypress','Taxodium distichum',5.00,'Trees')
INSERT [Merchandise] VALUES (2125,'Carnation','Dianthus caryophyllis',1.25,'Annuals')
INSERT [Merchandise] VALUES (5530,'Celosia','C. argentea Cristata',1.25,'Annuals')
INSERT [Merchandise] VALUES (5180,'Dahlia','Dahlia pinnata',1.25,'Annuals')
INSERT [Merchandise] VALUES (3071,'Daylily','Hemerocallis',3.25,'Perennials')
/* View everything starting with a "A" */
Select * from [Merchandise] where [Product Name] like 'A%'
/* View everything starting with a "A" thru "D" */
Select * from [Merchandise] where [Product Name] like '[ABCD]%'

Put this code in SQL Query Analyzer and it works!
But it didn't yesterday :| !
I finally figured out it had to do with the way I was testing it. I only transferred TOP 25 and didn't realize it was taking the TOP 25 by key code, not product number.
Mistake was created Table by

SELECT TOP 25 * INTO [Merchandise] from [OldMerchandise]
should have been
SELECT TOP 25 * INTO [Merchandise] from [OldMerchandise] ORDER BY [Product Name]

No comments:

Post a Comment