Showing posts with label field. Show all posts
Showing posts with label field. Show all posts

Monday, March 26, 2012

multiquery in a store procedure...

Hi, here is the problem...

I must create a store procedure that do the following...

1. select id_name,...'some other field' from table 'data' where 'criteria' =
@.parameter

2. use the result of the first selection to create another selection
combining that results with the table 'name' where id_name is null in the
result selection...

In other word I have a first query that use a passed parameter, the result
of that query should be combined this another query, and the result should
be return from the store procedure...

I can't realize how to write this 'simple' problem... can anyone help me?

Many thanks,
AlexAlessandro (giumalex@.tiscali.it) writes:
> I must create a store procedure that do the following...
> 1. select id_name,...'some other field' from table 'data' where
> 'criteria' = @.parameter
> 2. use the result of the first selection to create another selection
> combining that results with the table 'name' where id_name is null in the
> result selection...
> In other word I have a first query that use a passed parameter, the result
> of that query should be combined this another query, and the result should
> be return from the store procedure...

A simple solution is to use temp tables or table variables.

However, of you often can do this with a derived table, which conceptually
can be seen as a temp table, but physically it is never materialized.

Here is an example:

SELECT C.*
FROM Northwind..Customers C
JOIN (SELECT CustomerID
FROM Northwind..Orders
GROUP BY CustomerID
HAVING COUNT(*) > 20) O ON C.CustomerID = O.CustomerID

Lists all customer informations about customers that have placed more than
20 orders.

--
Erland Sommarskog, SQL Server MVP, sommar@.algonet.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||"Alessandro" <giumalex@.tiscali.it> wrote in message news:<g8tkc.30640$eR5.16238@.tornado.fastwebnet.it>...
> Hi, here is the problem...
>...
> I can't realize how to write this 'simple' problem... can anyone help me?
> Many thanks,
> Alex

Hi Alex.. to work with SQL , query and paramter look at this site :

Http://www.RealTimeInformatica.it/Stany

Bye Bye ...

ps: anche in Italiano !;)

Friday, March 23, 2012

multiquery in a store procedure...

Hi, here is the problem...

I must create a store procedure that do the following...

1. select id_name,...'some other field' from table 'data' where 'criteria' =
@.parameter

2. use the result of the first selection to create another selection
combining that results with the table 'name' where id_name is null in the
result selection...

In other word I have a first query that use a passed parameter, the result
of that query should be combined this another query, and the result should
be return from the store procedure...

I can't realize how to write this 'simple' problem... can anyone help me?

Many thanks,
AlexAlessandro (giumalex@.tiscali.it) writes:
> I must create a store procedure that do the following...
> 1. select id_name,...'some other field' from table 'data' where
> 'criteria' = @.parameter
> 2. use the result of the first selection to create another selection
> combining that results with the table 'name' where id_name is null in the
> result selection...
> In other word I have a first query that use a passed parameter, the result
> of that query should be combined this another query, and the result should
> be return from the store procedure...

A simple solution is to use temp tables or table variables.

However, of you often can do this with a derived table, which conceptually
can be seen as a temp table, but physically it is never materialized.

Here is an example:

SELECT C.*
FROM Northwind..Customers C
JOIN (SELECT CustomerID
FROM Northwind..Orders
GROUP BY CustomerID
HAVING COUNT(*) > 20) O ON C.CustomerID = O.CustomerID

Lists all customer informations about customers that have placed more than
20 orders.

--
Erland Sommarskog, SQL Server MVP, sommar@.algonet.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.aspsql

Multipurpose Foreign Key

I've got a field [user.unitID] that can be a foreign key on the table
[Base] *OR* the table [Command] depending on the value of [User.role]
(see "Structure," below).

Question 1: Is this poor DB design?
Question2: If this is okay DB design (or, if I can't change this DB),
how do I perform a join?

I started writing a sproc (see "Beginnings of sproc," below), which
will definitely work, once I get it set up, but when I do these sorts
of things, I later come to find that there was a straight SQL way to
do it. So, is there a straight SQL way to do this, building joins with
CASEs, or something like that?

Thanks,
Jamie

## Structure (simplified) ##

[USER]
userID
unitID
role -- values can be 'B' or 'C' referring to [base] or [command] tbl

[BASE]
ID
NAME

[COMMAND]
ID
NAME

## Beginnings of a sproc ##

GO
USE myDB
IF EXISTS (SELECT name FROM sysobjects
WHERE name = 'getSessionInfo' AND type = 'P')
DROP PROCEDURE getSessionInfo
GO
USE myDB
GO
CREATE PROCEDURE getSessionInfo
@.userID varchar(50),
@.password varchar(50)
AS

DECLARE @.myUnitType varchar(2);

SELECT @.myUnitType = unitType
FROM
[user]
WHERE userID = @.userID
AND [password] = @.password

... blah blah blahJamie Jackson (wasteNOSPAMbasket@.bigfoot.com) writes:
> I've got a field [user.unitID] that can be a foreign key on the table
> [Base] *OR* the table [Command] depending on the value of [User.role]
> (see "Structure," below).
> Question 1: Is this poor DB design?

It is certainly not the plain standard design. And the method has the
apparent advantage that you can use FOREIGN-KEY constraint to enforce
the integrity, but you need to rely on triggers.

But since I know very little of your business problem, I am hesitant
to label the design as outright bad, or even poor. What I can say, is
that had I had the problem, I would definitely have looked into a solution
that would have permitted me to use DRI, but that would definitely have
been a case of fitting the solution to the tool.

> Question2: If this is okay DB design (or, if I can't change this DB),
> how do I perform a join?

Depends a little on the output, but say you want user and name of
base or command:

SELECT u.name, u.role, rolename = coalece(b.name, c.name)
FROM users u
LEFT JOIN base b ON u.role = 'B'
AND u.unitid = b.unitid
LEFT JOIN command c ON u.role = 'C'
AND u.unitid = c.unitid

An alternative is to introduce a basecommand table, to gather common
information, but I don't know enough about your business problem to
say whether this is a good idea or not.

--
Erland Sommarskog, SQL Server MVP, sommar@.algonet.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||Jamie Jackson wrote:
> I've got a field [user.unitID] that can be a foreign key on the table
> [Base] *OR* the table [Command] depending on the value of [User.role]
> (see "Structure," below).
> Question 1: Is this poor DB design?
<snip
Yes. A table represents something. In your case a User, a Base or a
Command. In your design you specify whether a User can have a relation
with a Base or not. If it can have a relation, then this means there is
a foreign key column (or a relation table) for this specific relation.
For Command you make the same decision.

So in your case, User should have one column with a foreign key
constraint to Base, and another column with a foreign key constraint to
Command. You make the relations optional by allowing NULL values in the
foreign key columns.

If this is an Object Oriented design (for example, when Command extends
from Base), then you are in trouble, because OO and RDBMS don't map very
well.

Hope this helps,
Gert-Jan|||Thanks, Erland, that SQL was a nice tutorial on filtered joins and the
coalesce function, neither of which I've ever used.

Thanks,
Jamie

On Wed, 16 Jul 2003 21:54:51 +0000 (UTC), Erland Sommarskog
<sommar@.algonet.se> wrote:

>Jamie Jackson (wasteNOSPAMbasket@.bigfoot.com) writes:
>> I've got a field [user.unitID] that can be a foreign key on the table
>> [Base] *OR* the table [Command] depending on the value of [User.role]
>> (see "Structure," below).
>>
>> Question 1: Is this poor DB design?
>It is certainly not the plain standard design. And the method has the
>apparent advantage that you can use FOREIGN-KEY constraint to enforce
>the integrity, but you need to rely on triggers.
>But since I know very little of your business problem, I am hesitant
>to label the design as outright bad, or even poor. What I can say, is
>that had I had the problem, I would definitely have looked into a solution
>that would have permitted me to use DRI, but that would definitely have
>been a case of fitting the solution to the tool.
>> Question2: If this is okay DB design (or, if I can't change this DB),
>> how do I perform a join?
>Depends a little on the output, but say you want user and name of
>base or command:
>
> SELECT u.name, u.role, rolename = coalece(b.name, c.name)
> FROM users u
> LEFT JOIN base b ON u.role = 'B'
> AND u.unitid = b.unitid
> LEFT JOIN command c ON u.role = 'C'
> AND u.unitid = c.unitid
>An alternative is to introduce a basecommand table, to gather common
>information, but I don't know enough about your business problem to
>say whether this is a good idea or not.

Multipul Selections in a Parameter field

I have a report that I would like to allow the user to use the Ctrl key to select mutiple cost centers in a report parameter field. Does anyone know how this would be done
From http://www.developmentnow.com/g/115_2004_11_0_4_0/sql-server-reporting-services.ht
Posted via DevelopmentNow.com Group
http://www.developmentnow.comIf you are using 2005 why do you need a ctrl key for selection, instead you
can use the multiple check box to pick multiple values.
Amarnath
"Duvon Harper" wrote:
> I have a report that I would like to allow the user to use the Ctrl key to select mutiple cost centers in a report parameter field. Does anyone know how this would be done?
> From http://www.developmentnow.com/g/115_2004_11_0_4_0/sql-server-reporting-services.htm
> Posted via DevelopmentNow.com Groups
> http://www.developmentnow.com
>

Multiple-step OLE DB operation generated errors.

Database: SQL Server 2000 Standard (works fine)
Database: SQL Server 2005 Standard (fails)
Provider: SQLOLEDB
We can update recordset field (database: MS SQL 2000, client side cursor,
adLockOptimistic), regardless of the recordset's source (query or stored
procedure)
The problem begins with SQL 2005. We cannot update recordset field, if the
recordset is a result of stored procedure.
Error Source: Microsoft Cursor Engine
Error Description: Multiple-step operation generated errors. Check each
status value.> The problem begins with SQL 2005. We cannot update recordset field, if the
> recordset is a result of stored procedure.
Because that's not how you affect data. A recordset is for retrieving and
presenting data. If you want to change the data in the database, use a DML
statement (INSERT/UPDATE/DELETE). Better yet, call a stored procedure that
does that.
A|||Dmitriy Shapiro wrote:
> Database: SQL Server 2000 Standard (works fine)
> Database: SQL Server 2005 Standard (fails)
> Provider: SQLOLEDB
What development platform/language?
> We can update recordset field (database: MS SQL 2000, client side
> cursor, adLockOptimistic), regardless of the recordset's source
> (query or stored procedure)
> The problem begins with SQL 2005. We cannot update recordset field,
> if the recordset is a result of stored procedure.
I'm assuming you've used "SET NOCOUNT ON" in the procedure ...

> Error Source: Microsoft Cursor Engine
> Error Description: Multiple-step operation generated errors. Check
> each status value.
So have you looped through the connection's Errors collection to see the
error message(s)?
If you are developing for ASP, then I will echo Aaron's suggestion: use DML.
If it's a desktop application, then there are some valid reasons (handling
concurrency, etc.) for using a recordset to perform data maintenance.
If none of the above helps, you should post a repro script (DDL and
recordset code) to the group that is focussed on your development platform.
--
Microsoft MVP -- ASP/ASP.NET
Please reply to the newsgroup. The email account listed in my From
header is my spam trap, so I don't check it very often. You will get a
quicker response by posting to the newsgroup.|||Thanks for replies. Our firewall block all notifications. Sorry.
The changes in recordset are not going back to the database. They are only
for UI. This is a legasy code.
Language: VB 6.0
Platform: Windows XP and Win 2003
"Bob Barrows [MVP]" <reb01501@.NOyahoo.SPAMcom> wrote in message
news:ef4gCUrIGHA.3408@.TK2MSFTNGP12.phx.gbl...
> Dmitriy Shapiro wrote:
> What development platform/language?
> I'm assuming you've used "SET NOCOUNT ON" in the procedure ...
>
> So have you looped through the connection's Errors collection to see the
> error message(s)?
> If you are developing for ASP, then I will echo Aaron's suggestion: use
> DML.
> If it's a desktop application, then there are some valid reasons (handling
> concurrency, etc.) for using a recordset to perform data maintenance.
> If none of the above helps, you should post a repro script (DDL and
> recordset code) to the group that is focussed on your development
> platform.
> --
> Microsoft MVP -- ASP/ASP.NET
> Please reply to the newsgroup. The email account listed in my From
> header is my spam trap, so I don't check it very often. You will get a
> quicker response by posting to the newsgroup.
>|||Dmitriy Shapiro wrote:
> Thanks for replies. Our firewall block all notifications. Sorry.
' Data is trnasmitted but error messages are blocked? I don't think this is
possible.

> The changes in recordset are not going back to the database. They are
> only for UI. This is a legasy code.
I'm not sure I understand what you are saying here, or why it is relevant
that the code is legacy.

> Language: VB 6.0
> Platform: Windows XP and Win 2003
>
So you plan to follow up in a VB group ... ?
Try microsoft.public.vb.database or microsoft.public.vb.database.ado.
Also, you might try using SQL Profiler to trace the actual commands being
sent to the database by the application: it may provide a clue.
Bob Barrows
Microsoft MVP -- ASP/ASP.NET
Please reply to the newsgroup. The email account listed in my From
header is my spam trap, so I don't check it very often. You will get a
quicker response by posting to the newsgroup.|||> I'm not sure I understand what you are saying here
Here is an example:
'get recordset from database as result of "stored_procedure"
'GetData executes ADO command, with Client Side Cursor and optimistic
locking option
Set rs = GetData("stored_procedure")
'translate column1 to Spanish
'Our legasy code use this technique to translate some data, before
presenting them to the client
rs("column1").value = trnalsateToSpanish(rs("column1").value)
'show recordset in the grid
Display(rs)
These lines work fine when we connect to SQL Server 2000
They fail with SQL Server 2005

>why it is relevant
> that the code is legacy.
I would like to find solution that will have minimum impact on the code.
"Bob Barrows [MVP]" <reb01501@.NOyahoo.SPAMcom> wrote in message
news:OXigYR1IGHA.2704@.TK2MSFTNGP15.phx.gbl...
> Dmitriy Shapiro wrote:
> ' Data is trnasmitted but error messages are blocked? I don't think this
> is
> possible.
>
> I'm not sure I understand what you are saying here, or why it is relevant
> that the code is legacy.
>
> So you plan to follow up in a VB group ... ?
> Try microsoft.public.vb.database or microsoft.public.vb.database.ado.
> Also, you might try using SQL Profiler to trace the actual commands being
> sent to the database by the application: it may provide a clue.
> Bob Barrows
> --
> Microsoft MVP -- ASP/ASP.NET
> Please reply to the newsgroup. The email account listed in my From
> header is my spam trap, so I don't check it very often. You will get a
> quicker response by posting to the newsgroup.
>|||Dmitriy Shapiro wrote:
<snip>
Microsoft MVP -- ASP/ASP.NET
Please reply to the newsgroup. The email account listed in my From
header is my spam trap, so I don't check it very often. You will get a
quicker response by posting to the newsgroup.|||Dmitriy Shapiro wrote:
> Here is an example:
> 'get recordset from database as result of "stored_procedure"
> 'GetData executes ADO command, with Client Side Cursor and optimistic
> locking option
> Set rs = GetData("stored_procedure")
>
Unless you have set the connection's CursorLocation property to adUseClient,
this line will result in a default server-side forward-only cursor.
To have control over the cursor type, you must:
Set rs= New ADODB.Recordset
rs.CursorLocation=adUseClient
Then either use the command object as the source argument in the recordset's
Open method:
rs.Open cmd
or use the stored-procedure-as-connection-method technique to bypass the
creation of the explicit Command object:
cn.stored_procedure parm1,...parmN, rs
Bob Barrows
--
Microsoft MVP -- ASP/ASP.NET
Please reply to the newsgroup. The email account listed in my From
header is my spam trap, so I don't check it very often. You will get a
quicker response by posting to the newsgroup.|||Bob,

>Unless you have set the connection's CursorLocation property to
>adUseClient,
> this line will result in a default server-side forward-only cursor.
I do have MyDBConnection.CursorLocation = adUseClient
Before I was unable to update recordset regardless if was result of stored
procedure or query.
Now I can only do it if it result of the query.
This code works:
Set rs = GetData("select column1 from table1")
rs("column1").value = "abc"
And this code does not work with new SQL Server 2005, but works with SQL
Server 2000:
Set rs = GetData("stored_procedure")
rs("column1").value = "abc"
Thank you.
"Bob Barrows [MVP]" <reb01501@.NOyahoo.SPAMcom> wrote in message
news:epIvE21IGHA.208@.tk2msftngp13.phx.gbl...
> Dmitriy Shapiro wrote:
> Unless you have set the connection's CursorLocation property to
> adUseClient,
> this line will result in a default server-side forward-only cursor.
> To have control over the cursor type, you must:
> Set rs= New ADODB.Recordset
> rs.CursorLocation=adUseClient
> Then either use the command object as the source argument in the
> recordset's
> Open method:
> rs.Open cmd
> or use the stored-procedure-as-connection-method technique to bypass the
> creation of the explicit Command object:
> cn.stored_procedure parm1,...parmN, rs
> Bob Barrows
> --
> Microsoft MVP -- ASP/ASP.NET
> Please reply to the newsgroup. The email account listed in my From
> header is my spam trap, so I don't check it very often. You will get a
> quicker response by posting to the newsgroup.
>|||Dmitriy Shapiro wrote:
> Bob,
>
> I do have MyDBConnection.CursorLocation = adUseClient
> Before I was unable to update recordset regardless if was result of
> stored procedure or query.
> Now I can only do it if it result of the query.
> This code works:
> Set rs = GetData("select column1 from table1")
> rs("column1").value = "abc"
> And this code does not work with new SQL Server 2005, but works with
> SQL Server 2000:
> Set rs = GetData("stored_procedure")
>
I'm sorry, but without knowing what the GetData function and the stored
procedure look like, nobody will be able to help you. An I'm sure you are
going to be able to get more help from thhe VB experts in one of the VB
newsgroups.
Microsoft MVP -- ASP/ASP.NET
Please reply to the newsgroup. The email account listed in my From
header is my spam trap, so I don't check it very often. You will get a
quicker response by posting to the newsgroup.

Wednesday, March 21, 2012

Multiple variables

Hi
Our database has a series of tables that are all linked by a field called
company_code (amongst others). Occasionally data needs to be deleted and
this involves deleting multiple rows from some of these tables and updating
data in another table. I tend to wait until there are a few to do and then
do them all at once. To make the task less onerous I have saved a simple
script that does all the deletions for each code at once, a cut down version
is below:
/*Delete all pay data and make contact only*/
DECLARE @.code int
SET @.code = 12345
DELETEcompany_size
WHEREcompany_code = @.code
--Other deletions go in here
UPDATEcompany_basic
SETreport_status = null,
report_entry_urn = null,
next_rpt_archive = null,
/* Other fields to be updated... */
WHEREcompany_code = @.code
What I would like to be able to do is change the 'where' statements so that
they use the IN operator rather than the = operator. Is there a way to do
this using variables so I can assign a list of company codes to a variable
that can be used with an IN operator?
Thanks
Andy
On Wed, 13 Apr 2005 08:48:06 -0700, Andy wrote:

>Hi
>Our database has a series of tables that are all linked by a field called
>company_code (amongst others). Occasionally data needs to be deleted and
>this involves deleting multiple rows from some of these tables and updating
>data in another table. I tend to wait until there are a few to do and then
>do them all at once. To make the task less onerous I have saved a simple
>script that does all the deletions for each code at once, a cut down version
>is below:
>/*Delete all pay data and make contact only*/
>DECLARE @.code int
>SET @.code = 12345
>DELETEcompany_size
>WHEREcompany_code = @.code
>--Other deletions go in here
>UPDATEcompany_basic
>SETreport_status = null,
>report_entry_urn = null,
>next_rpt_archive = null,
>/* Other fields to be updated... */
>WHEREcompany_code = @.code
>What I would like to be able to do is change the 'where' statements so that
>they use the IN operator rather than the = operator. Is there a way to do
>this using variables so I can assign a list of company codes to a variable
>that can be used with an IN operator?
>Thanks
>Andy
>
Hi Andy,
To do that, you'll have to use dynamic SQL. Since this is in a script
that only you can execute, you don't have to worry about SQL Injection
in this case.
Rough outline:
/*Delete all pay data and make contact only*/
DECLARE @.codes nvarchar(40)
DECLARE @.SQL nvarchar(4000)
SET @.code = N'(12345,6789)'
SET @.sql = 'DELETEcompany_size
WHEREcompany_code IN ' + @.code
EXEC (@.sql)
--Other deletions go in here
SET @.sql = 'UPDATEcompany_basic
SETreport_status = null,
report_entry_urn = null,
next_rpt_archive = null,
/* Other fields to be updated... */
WHEREcompany_code IN ' + @.code
EXEC (@.sql)
In case you're tempted to use this technique in your production code as
well, read up on SQL injection and other dangers of this technique:
http://www.sommarskog.se/dynamic_sql.html
Best, Hugo
(Remove _NO_ and _SPAM_ to get my e-mail address)
|||Hi Hugo
Thanks very much for this - I've not tried it yet as I think there might be
a couple of typos that I want to confirm:
You declare a variable called @.codes, presumably all of my old instances of
@.code should now read @.codes instead.
Is the N in this line correct: SET @.code = N'(12345,6789)'?
I'm not brave enough to give it a go anyway!!!
Thanks again
"Hugo Kornelis" wrote:

> On Wed, 13 Apr 2005 08:48:06 -0700, Andy wrote:
>
> Hi Andy,
> To do that, you'll have to use dynamic SQL. Since this is in a script
> that only you can execute, you don't have to worry about SQL Injection
> in this case.
> Rough outline:
> /*Delete all pay data and make contact only*/
> DECLARE @.codes nvarchar(40)
> DECLARE @.SQL nvarchar(4000)
> SET @.code = N'(12345,6789)'
> SET @.sql = 'DELETEcompany_size
> WHEREcompany_code IN ' + @.code
> EXEC (@.sql)
> --Other deletions go in here
> SET @.sql = 'UPDATEcompany_basic
> SETreport_status = null,
> report_entry_urn = null,
> next_rpt_archive = null,
> /* Other fields to be updated... */
> WHEREcompany_code IN ' + @.code
> EXEC (@.sql)
>
> In case you're tempted to use this technique in your production code as
> well, read up on SQL injection and other dangers of this technique:
> http://www.sommarskog.se/dynamic_sql.html
> Best, Hugo
> --
> (Remove _NO_ and _SPAM_ to get my e-mail address)
>
|||On Thu, 14 Apr 2005 04:52:00 -0700, Andy wrote:

>Hi Hugo
>Thanks very much for this - I've not tried it yet as I think there might be
>a couple of typos that I want to confirm:
>You declare a variable called @.codes, presumably all of my old instances of
>@.code should now read @.codes instead.
Hi Andy,
My bad - since I adapted the script to work for more than one code at
once, I thought it'd be best to change the variable name from @.code to
@.codes - but after changing the first, I promptly forgot to change the
rest. <blush>

>Is the N in this line correct: SET @.code = N'(12345,6789)'?
Yes. I've changed the datatype to nvarchar (note: not just varchar, but
nvarchar), as is required for dynamic SQL. The N in fron of the string
constant means that this is also regarded as nchar data instead of plain
char data. (Nothing bad will happen if you leave out the N, nor if you
use character type varchar - but it will cuase SQL Server to do an
implicit conversion under the hood. I prefer to use explicit conversion,
or no conversion at all).

>I'm not brave enough to give it a go anyway!!!
Always test code suggestions on a test database. Make sure you have a
recent backup or another means to retore the data. And if possible,
enclose the code to be tested in a transaction, so that you can rollback
the changes if something goes awry.
Following the above advise for code you write yourself is not exactly a
bad idea either :-)
Best, Hugo
(Remove _NO_ and _SPAM_ to get my e-mail address)
|||Hi Hugo
Thanks for this. I've been out of the office the last few days so have only
just picked this up. Thanks for the advice as well!
Andy
"Hugo Kornelis" wrote:

> On Thu, 14 Apr 2005 04:52:00 -0700, Andy wrote:
>
> Hi Andy,
> My bad - since I adapted the script to work for more than one code at
> once, I thought it'd be best to change the variable name from @.code to
> @.codes - but after changing the first, I promptly forgot to change the
> rest. <blush>
>
> Yes. I've changed the datatype to nvarchar (note: not just varchar, but
> nvarchar), as is required for dynamic SQL. The N in fron of the string
> constant means that this is also regarded as nchar data instead of plain
> char data. (Nothing bad will happen if you leave out the N, nor if you
> use character type varchar - but it will cuase SQL Server to do an
> implicit conversion under the hood. I prefer to use explicit conversion,
> or no conversion at all).
>
> Always test code suggestions on a test database. Make sure you have a
> recent backup or another means to retore the data. And if possible,
> enclose the code to be tested in a transaction, so that you can rollback
> the changes if something goes awry.
> Following the above advise for code you write yourself is not exactly a
> bad idea either :-)
> Best, Hugo
> --
> (Remove _NO_ and _SPAM_ to get my e-mail address)
>
|||Hi Hugo
I'm getting a syntax error when running this script because oneof the fields
that gets updated is a char data type so:
--Update the various flags on the company basic table
SET @.sql = 'UPDATEcompany_basic
SETreport_status = null,
--Other fields being set to null
verify_svy_urn = null,
pay_or_contact = 'C',
year_end_date = null,
--Other fields being set to Null
WHEREcompany_code IN ' + @.codes
EXEC (@.sql)
As you can see it is because the quote before C is closing the string and so
on. Do I need to break the string at that point and concatenate it so that:
pay_or_contact = ' + 'C' + ', etc etc
or is there a way of getting SQL to ignore the string within the string?
Sorry I didn't include that bit in the initial question - I was trying to
cut down on the size of the post!
Thanks
Andy
"Hugo Kornelis" wrote:

> On Thu, 14 Apr 2005 04:52:00 -0700, Andy wrote:
>
> Hi Andy,
> My bad - since I adapted the script to work for more than one code at
> once, I thought it'd be best to change the variable name from @.code to
> @.codes - but after changing the first, I promptly forgot to change the
> rest. <blush>
>
> Yes. I've changed the datatype to nvarchar (note: not just varchar, but
> nvarchar), as is required for dynamic SQL. The N in fron of the string
> constant means that this is also regarded as nchar data instead of plain
> char data. (Nothing bad will happen if you leave out the N, nor if you
> use character type varchar - but it will cuase SQL Server to do an
> implicit conversion under the hood. I prefer to use explicit conversion,
> or no conversion at all).
>
> Always test code suggestions on a test database. Make sure you have a
> recent backup or another means to retore the data. And if possible,
> enclose the code to be tested in a transaction, so that you can rollback
> the changes if something goes awry.
> Following the above advise for code you write yourself is not exactly a
> bad idea either :-)
> Best, Hugo
> --
> (Remove _NO_ and _SPAM_ to get my e-mail address)
>
|||On Mon, 18 Apr 2005 09:09:02 -0700, Andy wrote:
(snip)
>As you can see it is because the quote before C is closing the string and so
>on. Do I need to break the string at that point and concatenate it so that:
>pay_or_contact = ' + 'C' + ', etc etc
>or is there a way of getting SQL to ignore the string within the string?
(snip)
Hi Andy,
You'll have to make sure that you embed a quote within the string. The
code passed to the EXEC (@.sql) needs quotes around the C to recognise it
as a literal. There are two ways to do that: either use the ASCII value
for the quote, or double the quote (one quote in a string is considered
a string delimiter, two consecutive quotes are considered one quote as
part of the string):
--Update the various flags on the company basic table
SET @.sql = 'UPDATEcompany_basic
SETreport_status = null,
--Other fields being set to null
verify_svy_urn = null,
pay_or_contact = ''C'',
year_end_date = null,
--Other fields being set to Null
WHEREcompany_code IN ' + @.codes
EXEC (@.sql)
or
--Update the various flags on the company basic table
SET @.sql = 'UPDATEcompany_basic
SETreport_status = null,
--Other fields being set to null
verify_svy_urn = null,
pay_or_contact = ' +CHAR(39)+ 'C' +CHAR(39)+ ',
year_end_date = null,
--Other fields being set to Null
WHEREcompany_code IN ' + @.codes
EXEC (@.sql)
Best, Hugo
(Remove _NO_ and _SPAM_ to get my e-mail address)
|||Thanks Hugo
This has worked perfectly - its going to save me an awful lot of time!!!
Andy
"Hugo Kornelis" wrote:

> On Mon, 18 Apr 2005 09:09:02 -0700, Andy wrote:
> (snip)
> (snip)
> Hi Andy,
> You'll have to make sure that you embed a quote within the string. The
> code passed to the EXEC (@.sql) needs quotes around the C to recognise it
> as a literal. There are two ways to do that: either use the ASCII value
> for the quote, or double the quote (one quote in a string is considered
> a string delimiter, two consecutive quotes are considered one quote as
> part of the string):
> --Update the various flags on the company basic table
> SET @.sql = 'UPDATEcompany_basic
> SETreport_status = null,
> --Other fields being set to null
> verify_svy_urn = null,
> pay_or_contact = ''C'',
> year_end_date = null,
> --Other fields being set to Null
> WHEREcompany_code IN ' + @.codes
> EXEC (@.sql)
> or
> --Update the various flags on the company basic table
> SET @.sql = 'UPDATEcompany_basic
> SETreport_status = null,
> --Other fields being set to null
> verify_svy_urn = null,
> pay_or_contact = ' +CHAR(39)+ 'C' +CHAR(39)+ ',
> year_end_date = null,
> --Other fields being set to Null
> WHEREcompany_code IN ' + @.codes
> EXEC (@.sql)
> Best, Hugo
> --
> (Remove _NO_ and _SPAM_ to get my e-mail address)
>

Monday, March 19, 2012

Multiple updates on multiple conditions?

Hi,

I'm looking for a way, if possible, to update a field to different values based on different criteria. For example, Field X should be A if condition 1 is true, it should be B if condition 2 is true, etc. I'm not sure if there's a way to use a CASE in an UPDATE statement?

Thanks

Maybe something like:

update urTable
set X = case when condition_1 = target1 then A
when condition_2 = target2 then B
else C
end
where filterColumn = someCondition

Multiple updates and Identity fields

I have a table used by multiple applications. One column is an Identify field and is also used as a Primary key. What is\are the best practices to use get the identity value returned after an INSERT made by my code.. I'm worried that if someone does an INSERT into the same table a "zillionth" of a second later than I did, that I could get their Identity value.

TIA,

Barkingdog

Are you using SQL2k5 ? THen you can use the new OUTPUT clause. Otherwise you should have a look on SCOPE_IDENTITY() which should fit your needs. But the new OUTPUT function should be more straight forward in your case.

HTH, JEns K. Suessmeyer.

http://www.sqlserver2005.de|||

Jens,

I looked up OUTPUT in sql 2k5 BOL: Here's an example that I found:

>>>
Copy Code
USE AdventureWorks;
GO
DECLARE @.MyTableVar table( ScrapReasonID smallint,
Name varchar(50),
ModifiedDate datetime);
INSERT Production.ScrapReason
OUTPUT INSERTED.ScrapReasonID, INSERTED.Name, INSERTED.ModifiedDate
INTO @.MyTableVar
VALUES (N'Operator error', GETDATE());

--1. Display the result set of the table variable.
SELECT ScrapReasonID, Name, ModifiedDate FROM @.MyTableVar;

--2. Display the result set of the table.
SELECT ScrapReasonID, Name, ModifiedDate
FROM Production.ScrapReason;
GO
>>>>

So with OUTPUT the ScrapReasonID from @.MyTableVar will hold the identity of the row just inserted. Is this correct?


What is the difference in output between queries 1 and 2? Shouldn't they be the same?

TIA,

Barkingdog

Multiple Update with multiple condition

I'm having an Employee table with a Salary field. How can we increate the
salary of the employees with following conditions:
1) salary between 1000 and 10000 : increase 25%
2) salary between 10000 and 20000 : increase 15%
3) salary between 20000 and 30000 : increase 5%

Surely you can create a cursor to solve this. But the question is, Is it
possible to solve this in a single query, if no what is most optimized
way?Try:

UPDATE Employee
SET salary = salary *
CASE
WHEN salary>=1000 AND salary<10000 THEN 1.25
WHEN salary>=10000 AND salary<20000 THEN 1.15
WHEN salary>=20000 AND salary<30000 THEN 1.5
END
WHERE salary>=1000 AND salary<30000

--
David Portas
SQL Server MVP
--|||Thanks friend|||Thanks friend|||Thank you friend

Monday, March 12, 2012

Multiple tables in same report?

Is it possible to use 2 tables in the same report with different dataset, but
able to pass one field as parameter from one table to the other one?
For example I have one table that has the field ITEM_ID and SALE. I have
another table that has the field TOTAL_COST. I want to use the ITEM_ID as
the parameter to get the TOTAL_COST in table 2. These 2 tables will be
aligned to look like one table.
Please help. Thanks in advance.Can't you do it in your storedprocedure?
I mean your storedprocedure returns your ITEM_ID and SALE and
TOTAL_COST(Grouped by ITEM_ID and SALE)?
HTH
ALI-R
"chang" <chang@.discussions.microsoft.com> wrote in message
news:CC8E3E28-7375-477A-82A4-3DA05C28973E@.microsoft.com...
> Is it possible to use 2 tables in the same report with different dataset,
but
> able to pass one field as parameter from one table to the other one?
> For example I have one table that has the field ITEM_ID and SALE. I have
> another table that has the field TOTAL_COST. I want to use the ITEM_ID as
> the parameter to get the TOTAL_COST in table 2. These 2 tables will be
> aligned to look like one table.
> Please help. Thanks in advance.|||ALI-R thanks for responding. The problem with combining the 2 queries into
one stored procedure is a problem because the second query has more records
in it and does not output the intended data output. For example if I combine
the 2 queries, the TOTALCOST field tends to be higher because of more
records. If I do it separately and only use the ITEM_ID field as parameters
then I get the intended output for whatever ITEM_ID it is.
I already have the 2 queries created into 2 stored procedures. Here is what
the 2 queries looks like:
Stored Procedure 1:
SELECT DISTINCT CUSTOMER.ITEM_ID, SUM(CUSTOMER.AMOUNT) AS
[SalesAmount]
FROM CUSTOMER INNER JOIN
CUSTOMER_SALE ON CUSTOMER.ORDER_ID = CUSTOMER_SALE.ORDER_ID
WHERE (CUSTOMER.ITEM_ID IS NOT NULL) AND (CUSTOMER.DATE BETWEEN @.STARTDATE
AND @.ENDDATE)
GROUP BY CUSTOMER.ITEM_ID
ORDER BY CUSTOMER.ITEM_ID
Stored Procedure 2:
SELECT SUM(MAT_COST + LAB_COST + BUR_COST + SER_COST) AS [Total Cost]
FROM INV_TRANSACTION
WHERE (TRANS_ID IN
(SELECT MAX(TRANS_ID)
FROM CUSTOMER, INV_TRANSACTION, CUSTOMER_SALE
WHERE CUSTOMER.ORDER_ID = INV_TRANSACTION.ORDER_ID AND
CUSTOMER_SALE.ORDER_ID = CUSTOMER.ORDER_ID AND CUSTOMER.ITEM_ID = @.ITEMID
AND (CUSTOMER.DATE BETWEEN @.STARTDATE AND @.ENDDATE)
GROUP BY CUSTOMER.ORDER_ID))
The @.ITEMID parameter is to be use to reference the ITEMID field from
dataset 1 which is the stored procedure 1. I was able to do this
successfully by using a subreport and pass the ITEMID field from the main
report to the subreport to be use in the parameter @.ITEMID. The problem came
up when it was time to sum the TOTALCOST field in the subreport and display
it in the main report.
I heard that it might be possible to use 2 tables or more in the main report
and pass the field from one table to the other one via parameters. The
question is how would I do this?
"ALI-R" wrote:
> Can't you do it in your storedprocedure?
> I mean your storedprocedure returns your ITEM_ID and SALE and
> TOTAL_COST(Grouped by ITEM_ID and SALE)?
> HTH
> ALI-R
> "chang" <chang@.discussions.microsoft.com> wrote in message
> news:CC8E3E28-7375-477A-82A4-3DA05C28973E@.microsoft.com...
> > Is it possible to use 2 tables in the same report with different dataset,
> but
> > able to pass one field as parameter from one table to the other one?
> >
> > For example I have one table that has the field ITEM_ID and SALE. I have
> > another table that has the field TOTAL_COST. I want to use the ITEM_ID as
> > the parameter to get the TOTAL_COST in table 2. These 2 tables will be
> > aligned to look like one table.
> >
> > Please help. Thanks in advance.
>
>|||You would have to use a subreport or have all the data returned by one STP.
You can have two datasets in one report but there is no way to link them
together.
Subreports are slow. I stuggled with this myself and ended up rewritting my
reporting STP's. It ends up that you return more data then needed but it in
one call to the DB unlike subreports (called STP for each detail). I would
create a table variable containing all the fields from both stp's, plus a
Flag field ie (1 = stp1, 2 = stp2), then populate the table from your
existing stp's, then in the report use the Flag fields in a table/list
Filter. Hope this helps, I dont like it either but just give yourself more
time to develop reports
"chang" wrote:
> ALI-R thanks for responding. The problem with combining the 2 queries into
> one stored procedure is a problem because the second query has more records
> in it and does not output the intended data output. For example if I combine
> the 2 queries, the TOTALCOST field tends to be higher because of more
> records. If I do it separately and only use the ITEM_ID field as parameters
> then I get the intended output for whatever ITEM_ID it is.
> I already have the 2 queries created into 2 stored procedures. Here is what
> the 2 queries looks like:
> Stored Procedure 1:
> SELECT DISTINCT CUSTOMER.ITEM_ID, SUM(CUSTOMER.AMOUNT) AS
> [SalesAmount]
> FROM CUSTOMER INNER JOIN
> CUSTOMER_SALE ON CUSTOMER.ORDER_ID = CUSTOMER_SALE.ORDER_ID
> WHERE (CUSTOMER.ITEM_ID IS NOT NULL) AND (CUSTOMER.DATE BETWEEN @.STARTDATE
> AND @.ENDDATE)
> GROUP BY CUSTOMER.ITEM_ID
> ORDER BY CUSTOMER.ITEM_ID
> Stored Procedure 2:
> SELECT SUM(MAT_COST + LAB_COST + BUR_COST + SER_COST) AS [Total Cost]
> FROM INV_TRANSACTION
> WHERE (TRANS_ID IN
> (SELECT MAX(TRANS_ID)
> FROM CUSTOMER, INV_TRANSACTION, CUSTOMER_SALE
> WHERE CUSTOMER.ORDER_ID = INV_TRANSACTION.ORDER_ID AND
> CUSTOMER_SALE.ORDER_ID = CUSTOMER.ORDER_ID AND CUSTOMER.ITEM_ID = @.ITEMID
> AND (CUSTOMER.DATE BETWEEN @.STARTDATE AND @.ENDDATE)
> GROUP BY CUSTOMER.ORDER_ID))
> The @.ITEMID parameter is to be use to reference the ITEMID field from
> dataset 1 which is the stored procedure 1. I was able to do this
> successfully by using a subreport and pass the ITEMID field from the main
> report to the subreport to be use in the parameter @.ITEMID. The problem came
> up when it was time to sum the TOTALCOST field in the subreport and display
> it in the main report.
> I heard that it might be possible to use 2 tables or more in the main report
> and pass the field from one table to the other one via parameters. The
> question is how would I do this?
> "ALI-R" wrote:
> > Can't you do it in your storedprocedure?
> >
> > I mean your storedprocedure returns your ITEM_ID and SALE and
> > TOTAL_COST(Grouped by ITEM_ID and SALE)?
> >
> > HTH
> > ALI-R
> >
> > "chang" <chang@.discussions.microsoft.com> wrote in message
> > news:CC8E3E28-7375-477A-82A4-3DA05C28973E@.microsoft.com...
> > > Is it possible to use 2 tables in the same report with different dataset,
> > but
> > > able to pass one field as parameter from one table to the other one?
> > >
> > > For example I have one table that has the field ITEM_ID and SALE. I have
> > > another table that has the field TOTAL_COST. I want to use the ITEM_ID as
> > > the parameter to get the TOTAL_COST in table 2. These 2 tables will be
> > > aligned to look like one table.
> > >
> > > Please help. Thanks in advance.
> >
> >
> >|||Kenwood, thanks for responding. I have created this with subreport as you
had done in the past also. It works great and yes very slow. The problem
came when trying to Sum the field and have it display in the main report.
I think what you suggested is probably what I need to do. I'm not really
clear with what you are describing though. If possible can you walk me
through what you are describing in detail? I'm new to SQL queries and
Reporting Services.
Let try to see if I can describe what you are recommending.
1) Create 1 stored procedure with temp table with the fields from my 2 old
stored procedure.
2) Create a Flag field for that temp table (not sure what flag field is).
3) Populate the temp table with my 2 stored procedure within the stored
procedure I created from step 1.
4) In reporting services use the flag fields in table/list filter
Not sure if this is what you meant, but if possible can you look at my 2
queries and provide a stored procedure example of what you described?
Thanks again.
"KENWOOD" wrote:
> You would have to use a subreport or have all the data returned by one STP.
> You can have two datasets in one report but there is no way to link them
> together.
> Subreports are slow. I stuggled with this myself and ended up rewritting my
> reporting STP's. It ends up that you return more data then needed but it in
> one call to the DB unlike subreports (called STP for each detail). I would
> create a table variable containing all the fields from both stp's, plus a
> Flag field ie (1 = stp1, 2 = stp2), then populate the table from your
> existing stp's, then in the report use the Flag fields in a table/list
> Filter. Hope this helps, I dont like it either but just give yourself more
> time to develop reports
> "chang" wrote:
> > ALI-R thanks for responding. The problem with combining the 2 queries into
> > one stored procedure is a problem because the second query has more records
> > in it and does not output the intended data output. For example if I combine
> > the 2 queries, the TOTALCOST field tends to be higher because of more
> > records. If I do it separately and only use the ITEM_ID field as parameters
> > then I get the intended output for whatever ITEM_ID it is.
> >
> > I already have the 2 queries created into 2 stored procedures. Here is what
> > the 2 queries looks like:
> >
> > Stored Procedure 1:
> >
> > SELECT DISTINCT CUSTOMER.ITEM_ID, SUM(CUSTOMER.AMOUNT) AS
> > [SalesAmount]
> > FROM CUSTOMER INNER JOIN
> > CUSTOMER_SALE ON CUSTOMER.ORDER_ID = CUSTOMER_SALE.ORDER_ID
> > WHERE (CUSTOMER.ITEM_ID IS NOT NULL) AND (CUSTOMER.DATE BETWEEN @.STARTDATE
> > AND @.ENDDATE)
> > GROUP BY CUSTOMER.ITEM_ID
> > ORDER BY CUSTOMER.ITEM_ID
> >
> > Stored Procedure 2:
> > SELECT SUM(MAT_COST + LAB_COST + BUR_COST + SER_COST) AS [Total Cost]
> > FROM INV_TRANSACTION
> > WHERE (TRANS_ID IN
> > (SELECT MAX(TRANS_ID)
> > FROM CUSTOMER, INV_TRANSACTION, CUSTOMER_SALE
> > WHERE CUSTOMER.ORDER_ID = INV_TRANSACTION.ORDER_ID AND
> > CUSTOMER_SALE.ORDER_ID = CUSTOMER.ORDER_ID AND CUSTOMER.ITEM_ID = @.ITEMID
> > AND (CUSTOMER.DATE BETWEEN @.STARTDATE AND @.ENDDATE)
> > GROUP BY CUSTOMER.ORDER_ID))
> >
> > The @.ITEMID parameter is to be use to reference the ITEMID field from
> > dataset 1 which is the stored procedure 1. I was able to do this
> > successfully by using a subreport and pass the ITEMID field from the main
> > report to the subreport to be use in the parameter @.ITEMID. The problem came
> > up when it was time to sum the TOTALCOST field in the subreport and display
> > it in the main report.
> >
> > I heard that it might be possible to use 2 tables or more in the main report
> > and pass the field from one table to the other one via parameters. The
> > question is how would I do this?
> >
> > "ALI-R" wrote:
> >
> > > Can't you do it in your storedprocedure?
> > >
> > > I mean your storedprocedure returns your ITEM_ID and SALE and
> > > TOTAL_COST(Grouped by ITEM_ID and SALE)?
> > >
> > > HTH
> > > ALI-R
> > >
> > > "chang" <chang@.discussions.microsoft.com> wrote in message
> > > news:CC8E3E28-7375-477A-82A4-3DA05C28973E@.microsoft.com...
> > > > Is it possible to use 2 tables in the same report with different dataset,
> > > but
> > > > able to pass one field as parameter from one table to the other one?
> > > >
> > > > For example I have one table that has the field ITEM_ID and SALE. I have
> > > > another table that has the field TOTAL_COST. I want to use the ITEM_ID as
> > > > the parameter to get the TOTAL_COST in table 2. These 2 tables will be
> > > > aligned to look like one table.
> > > >
> > > > Please help. Thanks in advance.
> > >
> > >
> > >|||You understand what I meant, by flag field I just mean I a Field that you set
in your STP and use in the report design and not a field the user will see.
very simple SQL statement to get you started, It looks like you know SQL well
enough to make it work. Hope this helps.
DECLARE @.myTempTable TABLE(a_field_1 int, a_field_2 int, a_field_3 int,
SelectID varchar(10))
INSERT INTO @.myTempTable(a_field_1,a_field_2,SelectID) VALUES (1,1,'Select1')
INSERT INTO @.myTempTable(a_field_3,SelectID) VALUES (2,'Select2')
SELECT * FROM @.myTempTable
Then in the report you filter on SelectID (Fields!SelectID.Value ='Select1') and it is like you have two datasets. Which is what your after
correct?
"chang" wrote:
> Kenwood, thanks for responding. I have created this with subreport as you
> had done in the past also. It works great and yes very slow. The problem
> came when trying to Sum the field and have it display in the main report.
> I think what you suggested is probably what I need to do. I'm not really
> clear with what you are describing though. If possible can you walk me
> through what you are describing in detail? I'm new to SQL queries and
> Reporting Services.
> Let try to see if I can describe what you are recommending.
> 1) Create 1 stored procedure with temp table with the fields from my 2 old
> stored procedure.
> 2) Create a Flag field for that temp table (not sure what flag field is).
> 3) Populate the temp table with my 2 stored procedure within the stored
> procedure I created from step 1.
> 4) In reporting services use the flag fields in table/list filter
> Not sure if this is what you meant, but if possible can you look at my 2
> queries and provide a stored procedure example of what you described?
> Thanks again.
> "KENWOOD" wrote:
> > You would have to use a subreport or have all the data returned by one STP.
> > You can have two datasets in one report but there is no way to link them
> > together.
> > Subreports are slow. I stuggled with this myself and ended up rewritting my
> > reporting STP's. It ends up that you return more data then needed but it in
> > one call to the DB unlike subreports (called STP for each detail). I would
> > create a table variable containing all the fields from both stp's, plus a
> > Flag field ie (1 = stp1, 2 = stp2), then populate the table from your
> > existing stp's, then in the report use the Flag fields in a table/list
> > Filter. Hope this helps, I dont like it either but just give yourself more
> > time to develop reports
> >
> > "chang" wrote:
> >
> > > ALI-R thanks for responding. The problem with combining the 2 queries into
> > > one stored procedure is a problem because the second query has more records
> > > in it and does not output the intended data output. For example if I combine
> > > the 2 queries, the TOTALCOST field tends to be higher because of more
> > > records. If I do it separately and only use the ITEM_ID field as parameters
> > > then I get the intended output for whatever ITEM_ID it is.
> > >
> > > I already have the 2 queries created into 2 stored procedures. Here is what
> > > the 2 queries looks like:
> > >
> > > Stored Procedure 1:
> > >
> > > SELECT DISTINCT CUSTOMER.ITEM_ID, SUM(CUSTOMER.AMOUNT) AS
> > > [SalesAmount]
> > > FROM CUSTOMER INNER JOIN
> > > CUSTOMER_SALE ON CUSTOMER.ORDER_ID = CUSTOMER_SALE.ORDER_ID
> > > WHERE (CUSTOMER.ITEM_ID IS NOT NULL) AND (CUSTOMER.DATE BETWEEN @.STARTDATE
> > > AND @.ENDDATE)
> > > GROUP BY CUSTOMER.ITEM_ID
> > > ORDER BY CUSTOMER.ITEM_ID
> > >
> > > Stored Procedure 2:
> > > SELECT SUM(MAT_COST + LAB_COST + BUR_COST + SER_COST) AS [Total Cost]
> > > FROM INV_TRANSACTION
> > > WHERE (TRANS_ID IN
> > > (SELECT MAX(TRANS_ID)
> > > FROM CUSTOMER, INV_TRANSACTION, CUSTOMER_SALE
> > > WHERE CUSTOMER.ORDER_ID = INV_TRANSACTION.ORDER_ID AND
> > > CUSTOMER_SALE.ORDER_ID = CUSTOMER.ORDER_ID AND CUSTOMER.ITEM_ID = @.ITEMID
> > > AND (CUSTOMER.DATE BETWEEN @.STARTDATE AND @.ENDDATE)
> > > GROUP BY CUSTOMER.ORDER_ID))
> > >
> > > The @.ITEMID parameter is to be use to reference the ITEMID field from
> > > dataset 1 which is the stored procedure 1. I was able to do this
> > > successfully by using a subreport and pass the ITEMID field from the main
> > > report to the subreport to be use in the parameter @.ITEMID. The problem came
> > > up when it was time to sum the TOTALCOST field in the subreport and display
> > > it in the main report.
> > >
> > > I heard that it might be possible to use 2 tables or more in the main report
> > > and pass the field from one table to the other one via parameters. The
> > > question is how would I do this?
> > >
> > > "ALI-R" wrote:
> > >
> > > > Can't you do it in your storedprocedure?
> > > >
> > > > I mean your storedprocedure returns your ITEM_ID and SALE and
> > > > TOTAL_COST(Grouped by ITEM_ID and SALE)?
> > > >
> > > > HTH
> > > > ALI-R
> > > >
> > > > "chang" <chang@.discussions.microsoft.com> wrote in message
> > > > news:CC8E3E28-7375-477A-82A4-3DA05C28973E@.microsoft.com...
> > > > > Is it possible to use 2 tables in the same report with different dataset,
> > > > but
> > > > > able to pass one field as parameter from one table to the other one?
> > > > >
> > > > > For example I have one table that has the field ITEM_ID and SALE. I have
> > > > > another table that has the field TOTAL_COST. I want to use the ITEM_ID as
> > > > > the parameter to get the TOTAL_COST in table 2. These 2 tables will be
> > > > > aligned to look like one table.
> > > > >
> > > > > Please help. Thanks in advance.
> > > >
> > > >
> > > >|||Ken,
Thanks for the example. However I'm still having problems. Here's what I did.
CREATE PROCEDURE SP_TEMPTABLE
AS
DECLARE @.TEMPTABLE TABLE(CUSTOMER_CODE NVARCHAR(40), SALE_AMOUNT VARCHAR(30)
, COST VARCHAR(30))
INSERT INTO @.TEMPTABLE(CUSTOMER_CODE, [SALE AMOUNT])
Exec CW_PRODUCT
INSERT INTO @.TEMPTABLE(COST)
Exec CW_TOTALCOST
SELECT * FROM @.TEMPTABLE
Here's the error that I'm getting:
"EXECUTE cannot be used as a source when inserting into a table variable."
I'm not clear with the example that you provided. I understand that you
created a temp table and insert some values that you put in. And for the
flag field it's Select1 and Select2. The question is how would I use my
stored procedures that I created to use with a 3rd stored procedure as a temp
table that you described.
"KENWOOD" wrote:
> You understand what I meant, by flag field I just mean I a Field that you set
> in your STP and use in the report design and not a field the user will see.
> very simple SQL statement to get you started, It looks like you know SQL well
> enough to make it work. Hope this helps.
> DECLARE @.myTempTable TABLE(a_field_1 int, a_field_2 int, a_field_3 int,
> SelectID varchar(10))
> INSERT INTO @.myTempTable(a_field_1,a_field_2,SelectID) VALUES (1,1,'Select1')
> INSERT INTO @.myTempTable(a_field_3,SelectID) VALUES (2,'Select2')
> SELECT * FROM @.myTempTable
>
> Then in the report you filter on SelectID (Fields!SelectID.Value => 'Select1') and it is like you have two datasets. Which is what your after
> correct?
>
> "chang" wrote:
> > Kenwood, thanks for responding. I have created this with subreport as you
> > had done in the past also. It works great and yes very slow. The problem
> > came when trying to Sum the field and have it display in the main report.
> >
> > I think what you suggested is probably what I need to do. I'm not really
> > clear with what you are describing though. If possible can you walk me
> > through what you are describing in detail? I'm new to SQL queries and
> > Reporting Services.
> >
> > Let try to see if I can describe what you are recommending.
> >
> > 1) Create 1 stored procedure with temp table with the fields from my 2 old
> > stored procedure.
> >
> > 2) Create a Flag field for that temp table (not sure what flag field is).
> >
> > 3) Populate the temp table with my 2 stored procedure within the stored
> > procedure I created from step 1.
> >
> > 4) In reporting services use the flag fields in table/list filter
> >
> > Not sure if this is what you meant, but if possible can you look at my 2
> > queries and provide a stored procedure example of what you described?
> >
> > Thanks again.
> >
> > "KENWOOD" wrote:
> >
> > > You would have to use a subreport or have all the data returned by one STP.
> > > You can have two datasets in one report but there is no way to link them
> > > together.
> > > Subreports are slow. I stuggled with this myself and ended up rewritting my
> > > reporting STP's. It ends up that you return more data then needed but it in
> > > one call to the DB unlike subreports (called STP for each detail). I would
> > > create a table variable containing all the fields from both stp's, plus a
> > > Flag field ie (1 = stp1, 2 = stp2), then populate the table from your
> > > existing stp's, then in the report use the Flag fields in a table/list
> > > Filter. Hope this helps, I dont like it either but just give yourself more
> > > time to develop reports
> > >
> > > "chang" wrote:
> > >
> > > > ALI-R thanks for responding. The problem with combining the 2 queries into
> > > > one stored procedure is a problem because the second query has more records
> > > > in it and does not output the intended data output. For example if I combine
> > > > the 2 queries, the TOTALCOST field tends to be higher because of more
> > > > records. If I do it separately and only use the ITEM_ID field as parameters
> > > > then I get the intended output for whatever ITEM_ID it is.
> > > >
> > > > I already have the 2 queries created into 2 stored procedures. Here is what
> > > > the 2 queries looks like:
> > > >
> > > > Stored Procedure 1:
> > > >
> > > > SELECT DISTINCT CUSTOMER.ITEM_ID, SUM(CUSTOMER.AMOUNT) AS
> > > > [SalesAmount]
> > > > FROM CUSTOMER INNER JOIN
> > > > CUSTOMER_SALE ON CUSTOMER.ORDER_ID = CUSTOMER_SALE.ORDER_ID
> > > > WHERE (CUSTOMER.ITEM_ID IS NOT NULL) AND (CUSTOMER.DATE BETWEEN @.STARTDATE
> > > > AND @.ENDDATE)
> > > > GROUP BY CUSTOMER.ITEM_ID
> > > > ORDER BY CUSTOMER.ITEM_ID
> > > >
> > > > Stored Procedure 2:
> > > > SELECT SUM(MAT_COST + LAB_COST + BUR_COST + SER_COST) AS [Total Cost]
> > > > FROM INV_TRANSACTION
> > > > WHERE (TRANS_ID IN
> > > > (SELECT MAX(TRANS_ID)
> > > > FROM CUSTOMER, INV_TRANSACTION, CUSTOMER_SALE
> > > > WHERE CUSTOMER.ORDER_ID = INV_TRANSACTION.ORDER_ID AND
> > > > CUSTOMER_SALE.ORDER_ID = CUSTOMER.ORDER_ID AND CUSTOMER.ITEM_ID = @.ITEMID
> > > > AND (CUSTOMER.DATE BETWEEN @.STARTDATE AND @.ENDDATE)
> > > > GROUP BY CUSTOMER.ORDER_ID))
> > > >
> > > > The @.ITEMID parameter is to be use to reference the ITEMID field from
> > > > dataset 1 which is the stored procedure 1. I was able to do this
> > > > successfully by using a subreport and pass the ITEMID field from the main
> > > > report to the subreport to be use in the parameter @.ITEMID. The problem came
> > > > up when it was time to sum the TOTALCOST field in the subreport and display
> > > > it in the main report.
> > > >
> > > > I heard that it might be possible to use 2 tables or more in the main report
> > > > and pass the field from one table to the other one via parameters. The
> > > > question is how would I do this?
> > > >
> > > > "ALI-R" wrote:
> > > >
> > > > > Can't you do it in your storedprocedure?
> > > > >
> > > > > I mean your storedprocedure returns your ITEM_ID and SALE and
> > > > > TOTAL_COST(Grouped by ITEM_ID and SALE)?
> > > > >
> > > > > HTH
> > > > > ALI-R
> > > > >
> > > > > "chang" <chang@.discussions.microsoft.com> wrote in message
> > > > > news:CC8E3E28-7375-477A-82A4-3DA05C28973E@.microsoft.com...
> > > > > > Is it possible to use 2 tables in the same report with different dataset,
> > > > > but
> > > > > > able to pass one field as parameter from one table to the other one?
> > > > > >
> > > > > > For example I have one table that has the field ITEM_ID and SALE. I have
> > > > > > another table that has the field TOTAL_COST. I want to use the ITEM_ID as
> > > > > > the parameter to get the TOTAL_COST in table 2. These 2 tables will be
> > > > > > aligned to look like one table.
> > > > > >
> > > > > > Please help. Thanks in advance.
> > > > >
> > > > >
> > > > >|||Ken,
I tried playing with it all day yesterday and still no luck. Here's what I
got so far, but when I try running it from Reporting Services, it doesn't
work:
CREATE PROC CW_PRODUCT_TEMP
@.STARTDATE NVARCHAR(10),
@.ENDDATE NVARCHAR(10)
AS
INSERT INTO #TempTable1
SELECT DISTINCT CUSTOMER.ITEM_ID, SUM(CUSTOMER.AMOUNT) AS [Sale Amount]
FROM CUSTOMER INNER JOIN
CUSTOMER_SALE ON CUSTOMER.ITEM_ID =CUSTOMER_SALE.ITEM_ID
WHERE (CUSTOMER.ITEM_ID IS NOT NULL) AND (CUSTOMER.SHIPPED_DATE BETWEEN
@.STARTDATE AND @.ENDDATE)
GROUP BY CUSTOMER.ITEM_ID
ORDER BY CUSTOMER.ITEM_ID
INSERT INTO #TempTable2
SELECT SUM(MAT_COST + LAB_COST + BUR_COST + SER_COST) AS [Total Cost]
FROM INV_TRANSACTION
WHERE (TRANS_ID IN
(SELECT MAX(trans_id)
FROM customer, inv_transaction,
customer_sale
WHERE customer.cust_order_id =INVENTORY_TRANS.order_id AND customer_sale.order_id =
customer.order_id AND
customer.line_no =inv_transaction.order_no AND inv_transaction.type = 'O' AND
inv_transaction.class ='I' AND customer.item_id = #TempTable1.item_id AND
(customer.shipped_date BETWEEN @.startdate and @.enddate)
GROUP BY customer.CUST_ORDER_ID,
customer.LINE_NO))
SELECT * FROM #TempTable2, #TempTable1
WHERE #TempTable2.item_id = #TempTable1.item_id
Error that i'm getting is:
"Invalid object name '#TempTable1'"
Please advise.
Thanks again.
"chang" wrote:
> Ken,
> Thanks for the example. However I'm still having problems. Here's what I did.
> CREATE PROCEDURE SP_TEMPTABLE
> AS
> DECLARE @.TEMPTABLE TABLE(CUSTOMER_CODE NVARCHAR(40), SALE_AMOUNT VARCHAR(30)
> , COST VARCHAR(30))
> INSERT INTO @.TEMPTABLE(CUSTOMER_CODE, [SALE AMOUNT])
> Exec CW_PRODUCT
> INSERT INTO @.TEMPTABLE(COST)
> Exec CW_TOTALCOST
> SELECT * FROM @.TEMPTABLE
> Here's the error that I'm getting:
> "EXECUTE cannot be used as a source when inserting into a table variable."
> I'm not clear with the example that you provided. I understand that you
> created a temp table and insert some values that you put in. And for the
> flag field it's Select1 and Select2. The question is how would I use my
> stored procedures that I created to use with a 3rd stored procedure as a temp
> table that you described.
>
> "KENWOOD" wrote:
> > You understand what I meant, by flag field I just mean I a Field that you set
> > in your STP and use in the report design and not a field the user will see.
> > very simple SQL statement to get you started, It looks like you know SQL well
> > enough to make it work. Hope this helps.
> >
> > DECLARE @.myTempTable TABLE(a_field_1 int, a_field_2 int, a_field_3 int,
> > SelectID varchar(10))
> >
> > INSERT INTO @.myTempTable(a_field_1,a_field_2,SelectID) VALUES (1,1,'Select1')
> > INSERT INTO @.myTempTable(a_field_3,SelectID) VALUES (2,'Select2')
> >
> > SELECT * FROM @.myTempTable
> >
> >
> > Then in the report you filter on SelectID (Fields!SelectID.Value => > 'Select1') and it is like you have two datasets. Which is what your after
> > correct?
> >
> >
> >
> > "chang" wrote:
> >
> > > Kenwood, thanks for responding. I have created this with subreport as you
> > > had done in the past also. It works great and yes very slow. The problem
> > > came when trying to Sum the field and have it display in the main report.
> > >
> > > I think what you suggested is probably what I need to do. I'm not really
> > > clear with what you are describing though. If possible can you walk me
> > > through what you are describing in detail? I'm new to SQL queries and
> > > Reporting Services.
> > >
> > > Let try to see if I can describe what you are recommending.
> > >
> > > 1) Create 1 stored procedure with temp table with the fields from my 2 old
> > > stored procedure.
> > >
> > > 2) Create a Flag field for that temp table (not sure what flag field is).
> > >
> > > 3) Populate the temp table with my 2 stored procedure within the stored
> > > procedure I created from step 1.
> > >
> > > 4) In reporting services use the flag fields in table/list filter
> > >
> > > Not sure if this is what you meant, but if possible can you look at my 2
> > > queries and provide a stored procedure example of what you described?
> > >
> > > Thanks again.
> > >
> > > "KENWOOD" wrote:
> > >
> > > > You would have to use a subreport or have all the data returned by one STP.
> > > > You can have two datasets in one report but there is no way to link them
> > > > together.
> > > > Subreports are slow. I stuggled with this myself and ended up rewritting my
> > > > reporting STP's. It ends up that you return more data then needed but it in
> > > > one call to the DB unlike subreports (called STP for each detail). I would
> > > > create a table variable containing all the fields from both stp's, plus a
> > > > Flag field ie (1 = stp1, 2 = stp2), then populate the table from your
> > > > existing stp's, then in the report use the Flag fields in a table/list
> > > > Filter. Hope this helps, I dont like it either but just give yourself more
> > > > time to develop reports
> > > >
> > > > "chang" wrote:
> > > >
> > > > > ALI-R thanks for responding. The problem with combining the 2 queries into
> > > > > one stored procedure is a problem because the second query has more records
> > > > > in it and does not output the intended data output. For example if I combine
> > > > > the 2 queries, the TOTALCOST field tends to be higher because of more
> > > > > records. If I do it separately and only use the ITEM_ID field as parameters
> > > > > then I get the intended output for whatever ITEM_ID it is.
> > > > >
> > > > > I already have the 2 queries created into 2 stored procedures. Here is what
> > > > > the 2 queries looks like:
> > > > >
> > > > > Stored Procedure 1:
> > > > >
> > > > > SELECT DISTINCT CUSTOMER.ITEM_ID, SUM(CUSTOMER.AMOUNT) AS
> > > > > [SalesAmount]
> > > > > FROM CUSTOMER INNER JOIN
> > > > > CUSTOMER_SALE ON CUSTOMER.ORDER_ID = CUSTOMER_SALE.ORDER_ID
> > > > > WHERE (CUSTOMER.ITEM_ID IS NOT NULL) AND (CUSTOMER.DATE BETWEEN @.STARTDATE
> > > > > AND @.ENDDATE)
> > > > > GROUP BY CUSTOMER.ITEM_ID
> > > > > ORDER BY CUSTOMER.ITEM_ID
> > > > >
> > > > > Stored Procedure 2:
> > > > > SELECT SUM(MAT_COST + LAB_COST + BUR_COST + SER_COST) AS [Total Cost]
> > > > > FROM INV_TRANSACTION
> > > > > WHERE (TRANS_ID IN
> > > > > (SELECT MAX(TRANS_ID)
> > > > > FROM CUSTOMER, INV_TRANSACTION, CUSTOMER_SALE
> > > > > WHERE CUSTOMER.ORDER_ID = INV_TRANSACTION.ORDER_ID AND
> > > > > CUSTOMER_SALE.ORDER_ID = CUSTOMER.ORDER_ID AND CUSTOMER.ITEM_ID = @.ITEMID
> > > > > AND (CUSTOMER.DATE BETWEEN @.STARTDATE AND @.ENDDATE)
> > > > > GROUP BY CUSTOMER.ORDER_ID))
> > > > >
> > > > > The @.ITEMID parameter is to be use to reference the ITEMID field from
> > > > > dataset 1 which is the stored procedure 1. I was able to do this
> > > > > successfully by using a subreport and pass the ITEMID field from the main
> > > > > report to the subreport to be use in the parameter @.ITEMID. The problem came
> > > > > up when it was time to sum the TOTALCOST field in the subreport and display
> > > > > it in the main report.
> > > > >
> > > > > I heard that it might be possible to use 2 tables or more in the main report
> > > > > and pass the field from one table to the other one via parameters. The
> > > > > question is how would I do this?
> > > > >
> > > > > "ALI-R" wrote:
> > > > >
> > > > > > Can't you do it in your storedprocedure?
> > > > > >
> > > > > > I mean your storedprocedure returns your ITEM_ID and SALE and
> > > > > > TOTAL_COST(Grouped by ITEM_ID and SALE)?
> > > > > >
> > > > > > HTH
> > > > > > ALI-R
> > > > > >
> > > > > > "chang" <chang@.discussions.microsoft.com> wrote in message
> > > > > > news:CC8E3E28-7375-477A-82A4-3DA05C28973E@.microsoft.com...
> > > > > > > Is it possible to use 2 tables in the same report with different dataset,
> > > > > > but
> > > > > > > able to pass one field as parameter from one table to the other one?
> > > > > > >
> > > > > > > For example I have one table that has the field ITEM_ID and SALE. I have
> > > > > > > another table that has the field TOTAL_COST. I want to use the ITEM_ID as
> > > > > > > the parameter to get the TOTAL_COST in table 2. These 2 tables will be
> > > > > > > aligned to look like one table.
> > > > > > >
> > > > > > > Please help. Thanks in advance.
> > > > > >
> > > > > >
> > > > > >

Friday, March 9, 2012

Multiple table query

I just inhertied a database. In it are multiple tables that keep track of a
users profile. In each table is a modified_date field. That date only
relates to that table and not the entire profile. There was never a central
modified_date for the user.
I need to be able to check the users profile to see when the last time they
made an update. I am looking for a way to query all the tables
modified_date and get the most recent one date.While you're busy preparing the DDL and some sample data, here's a wild gues
s:
select max(combined_set.modified_date) as last_modified_date
from (
select modified_date
,user_id
from table_1
union
select modified_date
,user_id
from table_1
union
select modified_date
,user_id
from table_1
-- ...add more tables here...
) combined_set
where (user_id = @.user_id)
ML|||If you don't like the way the question is presented then feel free not to
answer it. Adding wise ass comments doesn't help anyone.
"ML" <ML@.discussions.microsoft.com> wrote in message
news:B395E91D-77AB-4739-8712-E7A8AAF15508@.microsoft.com...
> While you're busy preparing the DDL and some sample data, here's a wild
> guess:
> select max(combined_set.modified_date) as last_modified_date
> from (
> select modified_date
> ,user_id
> from table_1
> union
> select modified_date
> ,user_id
> from table_1
> union
> select modified_date
> ,user_id
> from table_1
> -- ...add more tables here...
> ) combined_set
> where (user_id = @.user_id)
>
> ML|||On Wed, 7 Sep 2005 15:07:23 -0400, Brian wrote:

>If you don't like the way the question is presented then feel free not to
>answer it. Adding wise ass comments doesn't help anyone.
Hi Brian,
If you don't like the fact that the professionals in this group prefer
to help as good as possible, and that this can only be done if the
specifications are very clear, feel free to take your questions
elsewhere.
I've seen lots of threads that start with a vague question, then the
first answer isn't correct because the question wasn't exact enough, etc
etc. That can go on for days. What a waste of time for everyone
involved!
ML really deserves better than your brush-off. Instead of just asking
for better specifications, he ALSO posted a query that (to me, at least)
looks like it might do the job for you. Did you already try it?
If ML's suggestions is not working for you, then please post better
specs: table structure (as CREATE TABLE statements), sample data (as
INSERT statements) and required results. See www.aspfaq.com/5006 for
more details, and some useful hints and links.
Best, Hugo
--
(Remove _NO_ and _SPAM_ to get my e-mail address)|||Hugo -
Believe me I appreciate every answer I have ever gotten from this newsgroup.
But I see little snide comments like that all the time (in a variety of
newsgroups) and it isn't really necessary. People can simple say, as I have
seen, please provide 'this' information so we can get a better idea of what
you are really looking for.
"Hugo Kornelis" <hugo@.pe_NO_rFact.in_SPAM_fo> wrote in message
news:86iuh11vpom3uilukkv3kpuncjkdbue989@.
4ax.com...
> On Wed, 7 Sep 2005 15:07:23 -0400, Brian wrote:
>
> Hi Brian,
> If you don't like the fact that the professionals in this group prefer
> to help as good as possible, and that this can only be done if the
> specifications are very clear, feel free to take your questions
> elsewhere.
> I've seen lots of threads that start with a vague question, then the
> first answer isn't correct because the question wasn't exact enough, etc
> etc. That can go on for days. What a waste of time for everyone
> involved!
> ML really deserves better than your brush-off. Instead of just asking
> for better specifications, he ALSO posted a query that (to me, at least)
> looks like it might do the job for you. Did you already try it?
> If ML's suggestions is not working for you, then please post better
> specs: table structure (as CREATE TABLE statements), sample data (as
> INSERT statements) and required results. See www.aspfaq.com/5006 for
> more details, and some useful hints and links.
> Best, Hugo
> --
> (Remove _NO_ and _SPAM_ to get my e-mail address)

Saturday, February 25, 2012

multiple select in the parameter field in Crystal reports 8.5

I have a multiple select in the parameter field in Crystal reports 8.5 how do i check against that value in my SP?

Suppose I select 2 user from Drop down say

Mary
John

Are they comma seperated the way they r in Web based apps?
how do i build a SQL String based on the User criteria?Where is the dropdown - in Crystal (as a defined range of inputs) or in an application devloped from Vb or C++ or similar?
To use the VB example, when you populate a combo box, you can assign a value to the .ItemData property of the combo, and then return that to the report via the .ParameterFields collection exposed via the CR Active X control.
Say you populate your combo with data from a table:
RecordID Name
1 Fred
2 Mary
3 Joan
4 John
etc

then in VB code would be
...open recordset
...start looping thru records
cboTest.AddItem value_to_appear ' eg Fred
cboTest.ItemData(cboTest.NewIndex) = id 'eg 1
next

when you click on the combo, you can get the index and pass it to crystal
lngID = cboTest.ItemData(cboTest.ListIndex)

then in your code you can pass that to report when you open it, eg
Dim objPrintApp As CRAXDRT.Application
Dim objReport As CRAXDRT.Report
Dim objParamDefs As CRAXDRT.ParameterFieldDefinitions
Dim objParamDef As CRAXDRT.ParameterFieldDefinition

' code presumes you have an input parameter to your report named pID
' Set the report source
Set objPrintApp = New CRAXDRT.Application
Set objReport = objPrintApp.OpenReport(strReportSourcePath & strSource)
objPrintApp.LogOnServerEx put logon parameters here

Set objParamDefs = objReport.ParameterFields
For Each objParamDef In objParamDefs
With objParamDef
Select Case .ParameterFieldName
'It finds and sets the appropriate Crystal parameters.
Case "pID"
.SetCurrentValue lngID

' add other Case conditions here to handle other parameter names.

' Catch-all for others
Case Else
strInput = InputBox("Enter a value for '" & .ParameterFieldName & "'")
If strInput <> "" Then
.SetCurrentValue strInput
Else
Exit Sub
End If
End Select
End With
Next

objReport.PrintOut

hope this helps

dave|||Thks for ur prompt reply...but the drop down is in crystal reports 8.5

I am using Crystal reports 8.5 stand alone with enterprise server......i mean i not using VB or anything else as App dev.
I have SP in SQL server 2000

I need to select multiple values from the drop down of the parameter field.
how do I put those values in the drop down of the parameter field which needs to be passed to the SP?

How do I build the Sql query once the multiple values r selected? are the multiple values comma seperated??