473,657 Members | 2,686 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Need to declare multiple values

Alright, so I have this problem. I want to make it easy for me and
others to be able to run a query and easily choose whether we want
Merchants or NonMerchants. Previously, we would have to comment out
bits of code and would leave things messy (it would also leave room for
error). So, I'm thought DECLARE and SET would work. Wrong.

This is what I have....

DECLARE @Merchant VARCHAR

SET @Merchant = (Select CONVERT(VARCHAR , Id) + ','
FROM AdminAdvertiser TypesDDL
WHERE Id IN (1,3,4,5)
) // Includes Active, Out of Business, Cease to do business, Inactive

I've also tried...

SET @Merchant = '1,3,4,5'

Then, in the query itself I try:

WHERE AdminAdvertiser TypesDDL.Id = @Merchant
or
WHERE AdminAdvertiser TypesDDL.Id IN @Merchant
or
WHERE AdminAdvertiser TypesDDL.Id IN (@Merchant)
or
WHERE AdminAdvertiser TypesDDL.Id LIKE @Merchant

Either way, it will ONLY show me the merchants whose Id is 1. When I
make the query:

WHERE AdminAdvertiser TypesDDL.Id IN (1,3,4,5)

I finally get the desired results.

Any ideas or tips?

Thank you so much!

Oct 30 '06 #1
7 26339
MC
The problem is in the variable declaration. You stated DECLARE @Merchant
VARCHAR
which basically means varchar(1). That means your '1,2,3,4' got trimmed to
the '1'.
Try putting DECLARE @Merchant VARCHAR(100) or something like that.
MC

"Andrew Tatum" <an**********@g mail.comwrote in message
news:11******** *************@m 7g2000cwm.googl egroups.com...
Alright, so I have this problem. I want to make it easy for me and
others to be able to run a query and easily choose whether we want
Merchants or NonMerchants. Previously, we would have to comment out
bits of code and would leave things messy (it would also leave room for
error). So, I'm thought DECLARE and SET would work. Wrong.

This is what I have....

DECLARE @Merchant VARCHAR

SET @Merchant = (Select CONVERT(VARCHAR , Id) + ','
FROM AdminAdvertiser TypesDDL
WHERE Id IN (1,3,4,5)
) // Includes Active, Out of Business, Cease to do business, Inactive

I've also tried...

SET @Merchant = '1,3,4,5'

Then, in the query itself I try:

WHERE AdminAdvertiser TypesDDL.Id = @Merchant
or
WHERE AdminAdvertiser TypesDDL.Id IN @Merchant
or
WHERE AdminAdvertiser TypesDDL.Id IN (@Merchant)
or
WHERE AdminAdvertiser TypesDDL.Id LIKE @Merchant

Either way, it will ONLY show me the merchants whose Id is 1. When I
make the query:

WHERE AdminAdvertiser TypesDDL.Id IN (1,3,4,5)

I finally get the desired results.

Any ideas or tips?

Thank you so much!

Oct 30 '06 #2
Thanks MC!

However, I now get this error: Syntax error converting the varchar
value '1,3,4,5' to a column of data type int.

Any ideas?

Oct 30 '06 #3

1) start using the standard CAST() and not the proprietary CONVERT().

2) There is no such thing as a gernal purpose magical universal "id",
so your DDL that you did not post will make no sense as a data model.
The names are all wrong. A table cannot have a type -- that is an
attribute. The DDL is where the table is created, not a kind of table.
3) A SELECT statement has only one WHERE clause, not the OR-ed chain
you showed. What you wanted was something like this, assuming that
AdminAdvertiser s are logically different from mere Advertisers.

SELECT <col list>
FROM AdminAdvertiser s
WHERE foobar_type IN (1,2,3,4);

4) Syntax error converting the varchar value '1,3,4,5' to a column of
data type int. <<

Of course! Look at the string; it is full of commas so it cannot be
parsed as an INTEGER.

Your problem is that you do not understand that a column is always a
scalar value. You have no idea how to create a data model and a
newsgroup is not going to give you that kind of training.

See if you can get help from some who knows SQL and data modeling for a
few months. Your mental model is wrong.

Oct 30 '06 #4
Sorry that I do not use CAST. Convert works for the time being. I don't
consider myself to be "advanced" by any means, however, I don't think I
need some "basic training." Here is a look at the entire query, as it
may help you understand it easier.

DECLARE @startdate smalldatetime, @Merchant varchar, @NonMerchant
varchar

SET @startdate = '10/01/2006'; // Start Date
SET @Merchant = '1,3,4,5'; // Includes Active, Out of Business, Cease
to do business, Inactive
SET @NonMerchant = '2,6'; // Includes Inhouse, School Messengers

SELECT [Merchant],
[University],
CONVERT(Varchar , [Month]) + '/' + CONVERT(Varchar , [Year])
[SendOn],
SUM([Total Scheduled]) [Total Scheduled],
SUM([Total Rejected]) [Total Rejected],
SUM([Toal Received]) [Toal Received],
[Enrollment Message?]
FROM (
SELECT
MessageInfo.Adv ertiser [Merchant],
MessageInfo.Nam e [University],
DATEPART(month, MessageInfo.Sen dOn) [Month],
DATEPART(year, MessageInfo.Sen dOn) [Year],
MessageInfo.Tot al [Total Scheduled],
MessageInfo.Ref used [total rejected],
(MessageInfo.To tal - MessageInfo.Ref used) [Toal Received],
CASE WHEN AdMessageReques ts.IsEnrollment Message = 1 THEN
'Yes'
ELSE 'No'
END [Enrollment Message?]
FROM MessageInfo
JOIN AdMessageReques ts ON AdMessageReques ts.MessageId =
MessageInfo.id
JOIN Advertisers ON Advertisers.id = MessageInfo.Adv ertiserId
JOIN AdvertiserTypes ON Advertisers.Adv ertiserTypeId =
AdvertiserTypes .Id
WHERE MessageInfo.Sen dON < @startdate
AND Advertisers.Adv ertiserTypeId IN @Merchant
) mess

GROUP By [Merchant], [University], mess.[Month], mess.[Year],
[Enrollment Message?]
ORDER BY [Merchant], [University], mess.[Year], mess.[Month],
[Enrollment Message?]

Basically, I am trying to avoid this:

WHERE AdminAdvertiser List.Advertiser TypeId IN (
1, // (Name: Active)
// 2, // (Name: In-House)
3, // (Name: Out of Business)
4, // (Name: Cease to do Business)
5 // (Name: Inactive)
// 6, // (Name: School Messenger)
)

I have to comment things out all the time. It really makes no sense...
and it causes a lot of human error.

Oct 30 '06 #5
As per MC - varchar is 1 character.

In order to do IN (@Merchant) you will need to use dynamic SQL. the IN is
looking at a single value - the contents of @Merchant at the moment.

If you don't want to use dynamic SQL then split the string out into a set in
a table variable/temporary table and then you can join / use that in the IN.

--
Tony Rogerson
SQL Server MVP
http://sqlblogcasts.com/blogs/tonyrogerson - technical commentary from a SQL
Server Consultant
http://sqlserverfaq.com - free video tutorials
"Andrew Tatum" <an**********@g mail.comwrote in message
news:11******** *************@m 7g2000cwm.googl egroups.com...
Alright, so I have this problem. I want to make it easy for me and
others to be able to run a query and easily choose whether we want
Merchants or NonMerchants. Previously, we would have to comment out
bits of code and would leave things messy (it would also leave room for
error). So, I'm thought DECLARE and SET would work. Wrong.

This is what I have....

DECLARE @Merchant VARCHAR

SET @Merchant = (Select CONVERT(VARCHAR , Id) + ','
FROM AdminAdvertiser TypesDDL
WHERE Id IN (1,3,4,5)
) // Includes Active, Out of Business, Cease to do business, Inactive

I've also tried...

SET @Merchant = '1,3,4,5'

Then, in the query itself I try:

WHERE AdminAdvertiser TypesDDL.Id = @Merchant
or
WHERE AdminAdvertiser TypesDDL.Id IN @Merchant
or
WHERE AdminAdvertiser TypesDDL.Id IN (@Merchant)
or
WHERE AdminAdvertiser TypesDDL.Id LIKE @Merchant

Either way, it will ONLY show me the merchants whose Id is 1. When I
make the query:

WHERE AdminAdvertiser TypesDDL.Id IN (1,3,4,5)

I finally get the desired results.

Any ideas or tips?

Thank you so much!

Oct 31 '06 #6
Here goes for the string split...

create a sequence table (just numbers)

create table Seq (
rownumber int not null primary key clustered
)

set nocount on

declare @i int
set @i = 1
while @i <= 1000
begin
insert seq ( rownumber ) values( @i )
set @i = @i + 1

end

Now you can split the string

DECLARE @id_from_multis elect_list_box varchar(100)
SET @id_from_multis elect_list_box = ',11,22,33,44,5 5,' -- note
requirement for ',' at start and end of string.

DECLARE @merchant_id table ( id int not null )
insert @merchant_id ( id )
select id = substring( @id_from_multis elect_list_box, s.rownumber+1,
s2.rownumber-1 )
from seq s
inner join seq s2 on s2.rownumber = charindex( ',', substring(
@id_from_multis elect_list_box,
s.rownumber+1,
len(
@id_from_multis elect_list_box ) ) )
where substring( @id_from_multis elect_list_box, s.rownumber, 1 ) = ','

Now you can do this...

SELECT [Merchant],
[University],
CONVERT(Varchar , [Month]) + '/' + CONVERT(Varchar , [Year])
[SendOn],
SUM([Total Scheduled]) [Total Scheduled],
SUM([Total Rejected]) [Total Rejected],
SUM([Toal Received]) [Toal Received],
[Enrollment Message?]
FROM (
SELECT
MessageInfo.Adv ertiser [Merchant],
MessageInfo.Nam e [University],
DATEPART(month, MessageInfo.Sen dOn) [Month],
DATEPART(year, MessageInfo.Sen dOn) [Year],
MessageInfo.Tot al [Total Scheduled],
MessageInfo.Ref used [total rejected],
(MessageInfo.To tal - MessageInfo.Ref used) [Toal Received],
CASE WHEN AdMessageReques ts.IsEnrollment Message = 1 THEN
'Yes'
ELSE 'No'
END [Enrollment Message?]
FROM MessageInfo
JOIN AdMessageReques ts ON AdMessageReques ts.MessageId =
MessageInfo.id
JOIN Advertisers ON Advertisers.id = MessageInfo.Adv ertiserId
JOIN AdvertiserTypes ON Advertisers.Adv ertiserTypeId =
AdvertiserTypes .Id
WHERE MessageInfo.Sen dON < @startdate
AND Advertisers.Adv ertiserTypeId IN ( SELECT id FROM
@merchant_id )
) mess

GROUP By [Merchant], [University], mess.[Month], mess.[Year],
[Enrollment Message?]
ORDER BY [Merchant], [University], mess.[Year], mess.[Month],
[Enrollment Message?]

--
Tony Rogerson
SQL Server MVP
http://sqlblogcasts.com/blogs/tonyrogerson - technical commentary from a SQL
Server Consultant
http://sqlserverfaq.com - free video tutorials
"Tony Rogerson" <to**********@s qlserverfaq.com wrote in message
news:ei******** ***********@new s.demon.co.uk.. .
As per MC - varchar is 1 character.

In order to do IN (@Merchant) you will need to use dynamic SQL. the IN is
looking at a single value - the contents of @Merchant at the moment.

If you don't want to use dynamic SQL then split the string out into a set
in a table variable/temporary table and then you can join / use that in
the IN.

--
Tony Rogerson
SQL Server MVP
http://sqlblogcasts.com/blogs/tonyrogerson - technical commentary from a
SQL Server Consultant
http://sqlserverfaq.com - free video tutorials
"Andrew Tatum" <an**********@g mail.comwrote in message
news:11******** *************@m 7g2000cwm.googl egroups.com...
>Alright, so I have this problem. I want to make it easy for me and
others to be able to run a query and easily choose whether we want
Merchants or NonMerchants. Previously, we would have to comment out
bits of code and would leave things messy (it would also leave room for
error). So, I'm thought DECLARE and SET would work. Wrong.

This is what I have....

DECLARE @Merchant VARCHAR

SET @Merchant = (Select CONVERT(VARCHAR , Id) + ','
FROM AdminAdvertiser TypesDDL
WHERE Id IN (1,3,4,5)
) // Includes Active, Out of Business, Cease to do business, Inactive

I've also tried...

SET @Merchant = '1,3,4,5'

Then, in the query itself I try:

WHERE AdminAdvertiser TypesDDL.Id = @Merchant
or
WHERE AdminAdvertiser TypesDDL.Id IN @Merchant
or
WHERE AdminAdvertiser TypesDDL.Id IN (@Merchant)
or
WHERE AdminAdvertiser TypesDDL.Id LIKE @Merchant

Either way, it will ONLY show me the merchants whose Id is 1. When I
make the query:

WHERE AdminAdvertiser TypesDDL.Id IN (1,3,4,5)

I finally get the desired results.

Any ideas or tips?

Thank you so much!


Oct 31 '06 #7
On 30 Oct 2006 13:45:01 -0800, Andrew Tatum wrote:

(snip)
Here is a look at the entire query, as it
may help you understand it easier.
Hi Andrew,

Some comments inline and after the query.
>DECLARE @startdate smalldatetime, @Merchant varchar, @NonMerchant
varchar
Default length for varchar is 1. You'll probably want to include the
length in the declaration.
>SET @startdate = '10/01/2006'; // Start Date
Depending on language settings, @startdate might now be either january
10 or october 1. Use the yyyymmdd format ('20061001' or '20060110'),
that format is guaranteed to be unambiguous.
>SET @Merchant = '1,3,4,5'; // Includes Active, Out of Business, Cease
to do business, Inactive
SET @NonMerchant = '2,6'; // Includes Inhouse, School Messengers
Due to default length of varchar declaration, these variables will now
be equal to '1' and '2', resepctively.

(snip)
AND Advertisers.Adv ertiserTypeId IN @Merchant
That would result in a syntax error. I assume that the actual query has
parentheses around @Merchant:
AND Advertisers.Adv ertiserTypeId IN (@Merchant)

With the current code, this equates to
AdvertiserTypeI D IN ('1')
which will return only type 1. But adding a length to the declaration
won't fix this - with that chage, you'll have
AdvertiserTypeI D IN ('1,3,4,5')
instead of what you really need, which is one of these two
AdvertiserTypeI D IN ('1','3','4','5 ')
AdvertiserTypeI D IN (1,3,4,5)
(Which one you need depends on the datatype of the AdvertiserTypeI D
column)

Tony already suggested the use of dynamic SQL or a string splitter. If
you decide to use one of those techniques, then I suggest that you first
read Erland Sommarskog's excellent articles on these two techniques:
- http://www.sommarskog.se/dynamic_sql.html
- http://www.sommarskog.se/arrays-in-sql.html

However, I think that neither is the best solution in this case. From
your descriptions in this thread so far, I gather that you have
advertisers of different types, and that some types (1, 3, 4, and 5) are
considered to be merchants and other types (2 and 6) are non-merchants.

What will you do if a change in business requirements forces you to add
a new advertiser type (7). Change all your code and pray that you don't
miss a place where the lists of merchant vs non-merchant types is
included in a query?

Instead of hardcoding information in your code, why not store it in the
place that is designed to hold information - in a table. In your case, I
would add this column to your AdvertiserTypes table:
ALTER TABLE AdvertiserTypes
ADD IsMerchant char(1) NOT NULL DEFAULT 'Y' WITH VALUES;
ALTER TABLE AdvertiserTypes
ADD CONSTRAINT CK_IsMerchant CHECK (IsMerchant IN ('Y', 'N'));
UPDATE AdvertiserTypes
SET IsMerchant = 'N'
WHERE AdvertiserType IN (2, 6);

After that, chang this line from your query:
AND Advertisers.Adv ertiserTypeId IN @Merchant
to read like this:
AND AdvertiserTypes .IsMerchant = @MustBeMerchant
And of course, replace the current @Merchant and @NonMerchant variables
with a single char(1) parameter @MustBeMerchant that you can set to 'Y'
or 'N' to control which advertiser types must be selected. Wrap it all
in a stored procedure with @MustBeMerchant and @startdate as parameters
and POOF! - no more commenting out, no more human error.

--
Hugo Kornelis, SQL Server MVP
Oct 31 '06 #8

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

Similar topics

17
43915
by: Roland Hall | last post by:
Is there a way to return multiple values from a function without using an array? Would a dictionary object work better? -- Roland Hall /* This information is distributed in the hope that it will be useful, but without any warranty; without even the implied warranty of merchantability or fitness for a particular purpose. */ Technet Script Center - http://www.microsoft.com/technet/scriptcenter/ WSH 5.6 Documentation -...
16
17394
by: Nikolay Petrov | last post by:
How can I return multiple values from a custom function? TIA
9
10888
by: Karl O. Pinc | last post by:
I want to return multiple values, but not a set, only a single row, from a plpgsql function and I can't seem to get it to work. (I suppose I'd be happy to return a set, but I can't seem to make that work either. Anyway, what's wrong with this?) Version is: $ rpm -q postgresql
1
1730
by: method | last post by:
Hi all i am usiing this code to write mulitiple values to registery but it only write one value. could any one help me make this code so that it write multiple values to registery. Currently it only writes nickname but not pwd value!! I tried this but gave me error : 'Save the value to the registry SaveString HKEY_CURRENT_USER, "Software\xyz\" + Text6.Text, "nickname",+Text7.Text "pwd", strString
1
1441
by: brutusram | last post by:
I am trying to execute SP that has another SP in it that is being passed multiple values. I want to stay away from cursors but I cannot find another way to do this in 2005. BEGIN 1st STORED PROC ...running the 1st Proc info.... DECLARE @id UNIQUEIDENTIFIER SELECT @id=id
1
2194
by: wendy184 | last post by:
I'm used to using 2007 which allows multiple values in the lookup wizard, this helps hugely with my queries as the database i'm building has information on one parent who may have up to 5 kids. Now i'm building up a similar database in 2000 and could really use some help, 2000 won't allow multiple values in a lookup field which means if I have a parent who has more than one kid I cant store the details, I have a seperate table for both parent...
2
3665
ADezii
by: ADezii | last post by:
The incentive for this Tip was an Article by the amazing Allen Browne - I considered it noteworthy enough to post as The Tip of the Week in this Access Forum. Original Article by Allen Browne Traditionally, one has always thought that Functions can only return a single value, and for the most part that was true. Ever since Access 95, we gained the new functionality, through VBA, to have Functions return an entire Structure of values. A User...
0
3091
by: Maric Michaud | last post by:
Le Thursday 28 August 2008 03:43:16 norseman, vous avez écrit : Disctionaries are hash tables with a unique key and constant time lookup. What you want could be implemented as a complex data structures with as many dict as needed keys, but it seems you really want a relational table and a rdbms. This is exactly what they are for. A short example with the new python2.5 sqlite package :
1
11805
by: Anil Verma | last post by:
How to compare a SQL variable against multiple values: Here is the scenario; Declare @JobTitle varchar(10) Select @JobTitle = JobTitle from tableName where xxx=xxx Now I want to compare @JobTitle value against multiple strings without using OR in the IF statement?
0
8407
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8319
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8837
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8739
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
7347
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5638
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4329
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1969
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1732
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.