Showing posts with label query. Show all posts
Showing posts with label query. Show all posts

Thursday, March 29, 2012

Adjusting column width in queried dataset

I am trying to eliminate the extra space in columns that have been returned from a DB query...the tables have character lengths of 40, I would like to return just the necessary characters.

Thanks in advance.

Mark.

Did you try rtrim(ltrim(columnname) in the query?

cheers,

Andrew

|||

Thanks Andrew,

rtrim(columnname) did it.

Cheers,

Mark.

Tuesday, March 27, 2012

Ad-hoc Report Generation Based on the Input Query!

Hi all,

I want to generate the ad-hoc report using SQL Reporting Services 2000 or SQL Reporting Services 2005. But the Database Server will be SQL Server 2000. So, Can I send the query at run-time and then attach the data source to the actual report. In this case there will not be any columns etc. at design time with the value field mentioned in it. I know this is not the requirement for which this report tool is developed for. But still if this is possible through some other way round then pls. let me know. Actually we want one generic report which will satisfy all the tables, with diff. conditions mentioned in the select clause and where clause. So, is this possible with this reporting tool? Is there any way out where we want to come up with only one such report by manipulating the datasource of the report at run-time? Pls. let me know.

Thanks & Regards,

Dipali.

There may be a better way to do this in 2005 but the way I acheived dynamic columns in 2000 was to have a maximum number of columns (say 20) that take the value Column01, Column02....Column20 and make sure your data source returns the values under those names. Then you can also pass in the column names as a parameter. That's the only way I could come up with for producing a completely dynamic report.sql

Adhoc Query Tool for Sql Server

Hi !!
We are developing an application where we need a Query tool which allows customer to do Ad-Hoc or random query.. something similar to lets sayhttp://salebyowner.com/advancedSearch.php
We have few more options than this on which customer can do search.
I don't think dynamic query in C# code or something like that is going to help me. Am I right? Do we have to use any type of query tool or something for doing this?Hi love_luv,
Your example link shows a reasonably sophisticated query form written in PHP. But that doesn't mean PHP is a better database query tool than C# (or any other language for that matter).
PHP is just an application layer over top of some database. That database requires a completely different query language known as SQL (that has no direct link to PHP, C# or any other language).
The programmer in your example is simply using PHP to dyanmically costruct a SQL query statement (in text form) and passing it to their database to retrieve a result. C# (i.e., ASP.NET) can do that too.
In fact, with C# you can utilizeparameterized SQL queries for cleaner and safer SQL construction and execution.
The real trick behind sophisticated queries, of the type you're hoping to achieve, is a good familiarity with the SQL language (of the type native to your database brand,e.g., MS SQL Server uses a form of SQL known as Transact-SQL (a.k.a. TSql), and the knowledge to transform the user input from a webpage into said SQL.
Hope that helps.|||know, I understand that, its sophisticated query. I thought do we need to get some tool like Cognos etc etc for doing such query? More than parameterized query, I think its Dynamic or Adhoc query.|||You don't "need" a query tool at all, if you are familiar with SQL - regardless of how complex a query is. Visual Studio also query tools built in.

A special query tool or not, sophisticated or simple requirements - it all still comes down to a SQL statement to get your database results.
I found query tools useful once-upon-a-time for learning SQL, but I generally don't use them in my day-to-day programming now. You might find a tool useful to get an example of what your SQL text should look like, but once you have that then you use a language like C# to dynamically build the SQL text.
As an aside, "nearly" all database queries are dynamic (or adhoc) in nature. And using a parameterized query is just an optional format to make your dynamic (i.e., adhoc) queries easier to build (and safer to execute).
Hope that helps.|||So mean to say such a complex query is Dynamic Query written in C# code?
We really don't need any Commercial Query tool for Client end? We can use Web Forms to generate such query?
In couple of projects we implemented complex dynamic query, and that made us think if we need any tool or what? In our dynamic query, most of the time (99%) Select clause returns fix number of columns however, From Clause has base table and based on Where Conditions it may or may not join with other tables in data base.
In our version of dynamic query we builded WHERE clause in C#.
But how can we implement Join and WHERE using some proper structure.
Thanks|||

How one can handle dynamic SQL which has to perform JOIN with other tables.

Example I showed in my first post say has 2 - 3 tables:

PropertyListings and PropertyFeatures, PropertyLotFeatures

PropertyListings table gives me basic information I need to display.
PropertyFeatures and PropertyLotFeatures has information I need for advance search. I don't know which table to use and Join till user selects some features. based on Features selected for advance search I may have to Join:
1) PropertyListings with PropertyFeatures
2) PropertyListings with PropertyLotFeatures
3) PropertyListings with propertyFeatures and PropertyLotFeatures
I know once can right such query in C#, but is that how they do it or there is a better way? Am I missing something?

|||

Let me give an Example :

How about when there is Join Present. How whould you build Dynamic SQL? Do you need Dynamic SQL or there is a Better Way?
For Eg.
Table1 = Customers
Table2 = Interests
Table3 = Customers_Interests
Table4 = Activities
Table5 = Customers_Activities
Table3 holds Customers Interests.
Table5 holds Customers Activities
Lets say Customers Table has Data: C1, C2, C3, C4
Interests Table has Data: I1, I2, I3, I4
Cusomters_Interests has Data:
C1, I1
C1, I3
C1, I4
C2, I2
C2, I4
C3, I3
Activities Table has Data: A1, A2, A3, A4
Customers_Activities has Data:
C1, A1
C1, A4
C2, A3
C4, A1
Now lets say on my webpage I represent Interests and Activities as CheckBoxes.
Case 1:
I select Interests I1, I3, I4 but No Activities Selected. In this case my query has to join Customers, Interests and Customers_Interests Table
So query will be: Give me list of Customers with Interests I1, I3, I4
Case 2:
If I select Activities A1, A3 and No Interests, query whas to join Customers, Activities and Customers_Activities Table
Case 2:
If I select Interests I1 and Activities A1, in this case Query has to join Customers, Interests, Customers_Interests, Activities and Customers_Activities tables(all tables)
How would you write Query?
Looking for help!!!!!!!!!!!!!!!!!!!!!!!!!!!

ad-hoc query printing

Based on the tutorial in
http://msdn2.microsoft.com/en-us/library/ms170667.aspx
We have a prototype that works with our custom data extension in Reporting
Services 2005 such that we can generate a report based on a given query text.
Right now in order to view a report, we always publish the generated report
to a report server instance. Our question is whether we can do it without
using report server.
For example, does ReportViewer control (the local processing mode) help?
Our goal is to create a temporary report on the fly given a query such that
the user can print or export the report, which means that this temporary
report will be discarded as soon as the user is done with it. We would like
to know if this is possible.
Thanks in advance!Hi,
Welcome to use MSDN Managed Newsgroup!
From your descriptions, I understood you would like to whether it is
possible to create a temporary report for print only. If I have
misunderstood your concern, please feel free to point it out.
Unfortunately, Reporting Services do not have such funtionality to do so. I
wonder why do you need a Report on fly?
I have an interesting experience before that might give you some ideas. The
data source in my project was a remote linked server that need a lot of
time executing the complex query (cost about 5 minutes each time). When
perform the Email-Delivery Subscription to 10 or more different users, the
query will be executed 10 or more 5-minutes (around for 1 hours to complete
the email delivery subscription), which is obviously unacceptedable. Hence,
I will use DTS to transfer the data from linked server to local server
(cost 5 minutes) and then do the email-delivery subscription on local
tables, which is pretty cheap.
Hope this helps.
Sincerely yours,
Michael Cheng
Microsoft Online Partner Support
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
=====================================================This posting is provided "AS IS" with no warranties, and confers no rights.|||Hi,
Oops, sorry that I think I missed something
Here is an interesting article that shows VS 2005's new ReportViewer
control and its built-in Report Designer enable smart-client and Web page
designers to lay out, format, embed, export, and print interactive reports
without running a SQL Server Report Server.
Build Client-Side Reports Easily
http://msforums.ph/forums/91285/ShowPost.aspx
Sincerely yours,
Michael Cheng
Microsoft Online Partner Support
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
=====================================================This posting is provided "AS IS" with no warranties, and confers no rights.|||Thanks for your help. I found this walkthrough sample (similar to the one
you quoted below) from MSDN2 as well
http://msdn2.microsoft.com/en-us/library/ms251724.aspx
This is useful tutorial for us. However, I need to generate such report on
the fly ... that is, the dataset and datatable etc will be generated at
run-time. Is this even possible?
In addition, is there any tutorial on generating RDLC programmatically?
Thanks
Jenny
"Michael Cheng [MSFT]" wrote:
> Hi,
> Oops, sorry that I think I missed something
> Here is an interesting article that shows VS 2005's new ReportViewer
> control and its built-in Report Designer enable smart-client and Web page
> designers to lay out, format, embed, export, and print interactive reports
> without running a SQL Server Report Server.
> Build Client-Side Reports Easily
> http://msforums.ph/forums/91285/ShowPost.aspx
>
> Sincerely yours,
> Michael Cheng
> Microsoft Online Partner Support
> When responding to posts, please "Reply to Group" via your newsreader so
> that others may learn and benefit from your issue.
> =====================================================> This posting is provided "AS IS" with no warranties, and confers no rights.
>
>|||Actually, I just found out about the LocalReport class from
http://msdn2.microsoft.com/en-us/library/microsoft.reporting.winforms.localreport.aspx
Do you know of any example of how to use it? Say I already have a dataset
or a datatable or a collection of business objects (can't seem to find more
about what exactly a business object is).
Thanks in advance!
"yinjennytam@.newsgroup.nospam" wrote:
> Thanks for your help. I found this walkthrough sample (similar to the one
> you quoted below) from MSDN2 as well
> http://msdn2.microsoft.com/en-us/library/ms251724.aspx
> This is useful tutorial for us. However, I need to generate such report on
> the fly ... that is, the dataset and datatable etc will be generated at
> run-time. Is this even possible?
> In addition, is there any tutorial on generating RDLC programmatically?
> Thanks
> Jenny
>
>
> "Michael Cheng [MSFT]" wrote:
> > Hi,
> >
> > Oops, sorry that I think I missed something
> >
> > Here is an interesting article that shows VS 2005's new ReportViewer
> > control and its built-in Report Designer enable smart-client and Web page
> > designers to lay out, format, embed, export, and print interactive reports
> > without running a SQL Server Report Server.
> >
> > Build Client-Side Reports Easily
> > http://msforums.ph/forums/91285/ShowPost.aspx
> >
> >
> >
> > Sincerely yours,
> >
> > Michael Cheng
> > Microsoft Online Partner Support
> >
> > When responding to posts, please "Reply to Group" via your newsreader so
> > that others may learn and benefit from your issue.
> > =====================================================> > This posting is provided "AS IS" with no warranties, and confers no rights.
> >
> >
> >|||Hi,
To create a RDLC file, you may refer the article below
Creating Client Report Definition (.rdlc) Files
http://msdn2.microsoft.com/en-us/library/ms252067(en-US,VS.80).aspx
Converting RDL and RDLC Files
http://msdn2.microsoft.com/en-us/library/ms252109(en-US,VS.80).aspx
If you encounter any difficulties in the walkthrough, please let me know
the detail step you meet the error.
Sincerely yours,
Michael Cheng
Microsoft Online Partner Support
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
=====================================================This posting is provided "AS IS" with no warranties, and confers no rights.|||Thanks Michael for the links. I did take a look at both and did try some
walkthrough tutorials. They are great and now I understand more about
ReportViewer controls in general.
However, my problem is still not resolved. I guess I can rephrase it a bit
to let you understand it more:
(1) I need to generate the RDLC file programmatically because I don't know
the report fields at design time
(2) The same applies to the report data source, and I have a way to run a
query to get a System.Data.DataTable object which I can use as the report
data source, but again this depends on the search query, which I don't know
until run-time
I have attempted to modify the walkthrough from
http://msdn2.microsoft.com/en-us/library/ms251784(en-US,VS.80).aspx
But instead of creating the rdlc file using the UI, I created the RDLC file
based on the tutorial from
http://msdn2.microsoft.com/en-us/library/ms170667(en-US,SQL.90).aspx
Again, I just renamed this file using the *.rdlc extension instead of *.rdl
and save it somewhere in my local system.
As I mentioned above, given a query, I can create a System.Data.DataTable on
the fly and modified the sample code such that I commented out the followings
from Form1.Designer.cs:
//this.reportViewer1.LocalReport.DataSources.Add(reportDataSource1);
//this.reportViewer1.LocalReport.ReportEmbeddedResource ="BusinessObject.Report1.rdlc";
and added the following lines to Form1_Load() just before the line
this.reportViewer1.RefreshReport();
this.reportViewer1.LocalReport.DataSources.Add(new
ReportDataSource("Sales", datatable));
this.reportViewer1.LocalReport.ReportPath =@."C:\Development\trials\BusinessObject\BusinessObject\mysales.rdlc";
When I ran the app, I got the following error:
"A data source instance has not been supplied for the data source 'DataSet1'"
First of all, am I in the wrong track? Can I actually programmatically
create an RDL file and simply renamed it as RDLC. What else do I need to do
programmatically (not through adding it to the project as indicated by the
walkthrough)?
Second of all, what am I missing? Is it possible to supply the DataTable
(report data source) programmatically?
Thanks a lot for reading my long post.
Jenny
"Michael Cheng [MSFT]" wrote:
> Hi,
> To create a RDLC file, you may refer the article below
> Creating Client Report Definition (.rdlc) Files
> http://msdn2.microsoft.com/en-us/library/ms252067(en-US,VS.80).aspx
> Converting RDL and RDLC Files
> http://msdn2.microsoft.com/en-us/library/ms252109(en-US,VS.80).aspx
> If you encounter any difficulties in the walkthrough, please let me know
> the detail step you meet the error.
>
> Sincerely yours,
> Michael Cheng
> Microsoft Online Partner Support
> When responding to posts, please "Reply to Group" via your newsreader so
> that others may learn and benefit from your issue.
> =====================================================> This posting is provided "AS IS" with no warranties, and confers no rights.
>|||Actually I've figured it out myself! :-)
When I added a new ReportDataSource object, I should have named it
'DataSet1' to associate that with my RDLC file.
Jenny
"yinjennytam@.newsgroup.nospam" wrote:
> Thanks Michael for the links. I did take a look at both and did try some
> walkthrough tutorials. They are great and now I understand more about
> ReportViewer controls in general.
> However, my problem is still not resolved. I guess I can rephrase it a bit
> to let you understand it more:
> (1) I need to generate the RDLC file programmatically because I don't know
> the report fields at design time
> (2) The same applies to the report data source, and I have a way to run a
> query to get a System.Data.DataTable object which I can use as the report
> data source, but again this depends on the search query, which I don't know
> until run-time
> I have attempted to modify the walkthrough from
> http://msdn2.microsoft.com/en-us/library/ms251784(en-US,VS.80).aspx
> But instead of creating the rdlc file using the UI, I created the RDLC file
> based on the tutorial from
> http://msdn2.microsoft.com/en-us/library/ms170667(en-US,SQL.90).aspx
> Again, I just renamed this file using the *.rdlc extension instead of *.rdl
> and save it somewhere in my local system.
> As I mentioned above, given a query, I can create a System.Data.DataTable on
> the fly and modified the sample code such that I commented out the followings
> from Form1.Designer.cs:
> //this.reportViewer1.LocalReport.DataSources.Add(reportDataSource1);
> //this.reportViewer1.LocalReport.ReportEmbeddedResource => "BusinessObject.Report1.rdlc";
> and added the following lines to Form1_Load() just before the line
> this.reportViewer1.RefreshReport();
> this.reportViewer1.LocalReport.DataSources.Add(new
> ReportDataSource("Sales", datatable));
> this.reportViewer1.LocalReport.ReportPath => @."C:\Development\trials\BusinessObject\BusinessObject\mysales.rdlc";
>
> When I ran the app, I got the following error:
> "A data source instance has not been supplied for the data source 'DataSet1'"
>
> First of all, am I in the wrong track? Can I actually programmatically
> create an RDL file and simply renamed it as RDLC. What else do I need to do
> programmatically (not through adding it to the project as indicated by the
> walkthrough)?
> Second of all, what am I missing? Is it possible to supply the DataTable
> (report data source) programmatically?
>
> Thanks a lot for reading my long post.
> Jenny
>
>
>
> "Michael Cheng [MSFT]" wrote:
> > Hi,
> >
> > To create a RDLC file, you may refer the article below
> >
> > Creating Client Report Definition (.rdlc) Files
> > http://msdn2.microsoft.com/en-us/library/ms252067(en-US,VS.80).aspx
> >
> > Converting RDL and RDLC Files
> > http://msdn2.microsoft.com/en-us/library/ms252109(en-US,VS.80).aspx
> >
> > If you encounter any difficulties in the walkthrough, please let me know
> > the detail step you meet the error.
> >
> >
> > Sincerely yours,
> >
> > Michael Cheng
> > Microsoft Online Partner Support
> >
> > When responding to posts, please "Reply to Group" via your newsreader so
> > that others may learn and benefit from your issue.
> > =====================================================> > This posting is provided "AS IS" with no warranties, and confers no rights.
> >
> >|||Hi Jenny,
Thanks for your prompt update and it's great to hear you have resovled it
now!! And thanks so much for sharing this information with us.
Sincerely yours,
Michael Cheng
Microsoft Online Partner Support
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
=====================================================This posting is provided "AS IS" with no warranties, and confers no rights.

AdHoc Query faster than Stored Proc?

Yesterday i face a strange SQL Server 2000 behaviour :-(

I had a query that was wrapped inside a stored procedure, as usual.
Suddenly, the stored procedure execution time raised from 9 secs to 80.

So to understand where the problem was i cut and pasted the sp body's into a new query analyzer window an then executed it again. Speed back to 9 secs.
Tried stored procedure again, and speed again set to 80 secs.

Tried to recompile sp. Nothing. Tried to restart SQL Server. Nothing. Tried to DROP & RE-CREATE sp. Done! Speed again at 9 secs.

My collegue asked me "why?", but i had no words. :confused: Do you have any explanation?the stored proc was past its "best before" date

like, if you look in your fridge and the milk says april 2003, you have to throw it out and buy some more

;)|||Well, that was what i exactly did. Now i can drink milk safely, but i'd like to prevent this situation again if it's possibile.

It's always frustrating when things happen and I cannot understand why :(|||It's always frustrating when things happen and I cannot understand why :(boy, i know that feeling

switch from milk to bourbon -- keeps forever :)

trouble is, i always finish it, and have to go out for more...|||See Bart Duncan's notes on parameter sniffing here http://www.examnotes.net/article48335.html|||Thanks for the link. Though very interesting i was already aware of that problem, and in fact i tried to run the body of the stored procedure using parameters to closely simulate the behaviour of the stored procedure.

Since the sp was executed with WITH RECOMPILE i expected the same execution plan of the ad-hoc query (that is what normally happens), but this time SQL Server produced two different execution plans.

UPDATE:
mmm...i've read more deeply the info at the link i've told me and seems that the problem was really parameter sniffing. a BIG thanks! :)

Sunday, March 25, 2012

Additional Information

Also, some people do not have middle names, how would I write the query to
pull this out? Thanks again.
"Mike Collins" wrote:

> In the following query, I will be making 6 joins for each ID in the Proble
ms
> table to get a person's full name from our personnel table. Is there anoth
er
> way to do this than with the query I have below?
> Select TPRTitle, p1.FirstName + ' ' + p1.LastName As Originator,
> p2.FirstName + ' ' + p2.MiddleName + ' ' + p2.LastName As Screener
> From TPRs t
> Join common..personnel p1 On p1.PersonnelID = t.OriginatorID
> Join common..personnel p2 On p2.PersonnelID = t.ScreenerID
> ...
> CREATE TABLE [Personnel] (
> [PersonnelID] uniqueidentifier ROWGUIDCOL NOT NULL CONSTRAINT
> [DF_Personnel_PersonnelID] DEFAULT (newid()),
> [OrganizationID] [uniqueidentifier] NOT NULL ,
> [Title] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
> [FirstName] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
> [MiddleName] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
> [LastName] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
> [Service] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
> [OfficeSymbol] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
> [Notes] [text] COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
> [EmailAddress] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
> [LastModified] [datetime] NOT NULL ,
> CONSTRAINT [PK_Personnel] PRIMARY KEY CLUSTERED
> (
> [PersonnelID]
> ) WITH FILLFACTOR = 90 ON [PRIMARY]
> ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
> GO
>
> CREATE TABLE [Problems] (
> [ProblemID] uniqueidentifier ROWGUIDCOL NOT NULL CONSTRAINT
> [DF_TPRs_TPRID] DEFAULT (newid()),
> [OriginatorID] [uniqueidentifier] NOT NULL ,
> [ClassifiedByID] [uniqueidentifier] NOT NULL ,
> [ScreenerID] [uniqueidentifier] NOT NULL ,
> [SubjectMatterExpertID] [uniqueidentifier] NOT NULL ,
> [TestDirectorID] [uniqueidentifier] NOT NULL ,
> [TestEventID] [uniqueidentifier] NOT NULL ,
> [Title] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
> [Location] [varchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
> [Function] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
> [OS] [varchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
> [ProblemSource] [text] COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
> [SequenceOfEvents] [text] COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
> [ProblemDescription] [text] COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
> [WorkAround] [text] COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
> CONSTRAINT [PK_tblTPRs] PRIMARY KEY CLUSTERED
> (
> [ProblemID]
> ) WITH FILLFACTOR = 90 ON [PRIMARY] ,
> CONSTRAINT [FK_TPRs_TestEvents] FOREIGN KEY
> (
> [TestEventID]
> ) REFERENCES [TestEvents] (
> [TestEventID]
> )
> ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
> GO
>"Mike Collins" <MikeCollins@.discussions.microsoft.com> wrote in message
news:5C6CE19B-3FCE-422E-B546-3A1FDC7DD28B@.microsoft.com...
> Also, some people do not have middle names, how would I write the query to
> pull this out? Thanks again.
>
> "Mike Collins" wrote:
>
From where I sit, you will need to do the joins. A couple of suggestions
however.
1. Use ISNULL for the MiddleName column. If it is empty, you will not get
a row back because by default NULL Concatenation returns NULL. So
something like: ISNULL(p1.FirstName, '') + ' ' + ISNULL(p1.MiddleName,
'')...
2. Since I don't see any FK constraints in the Problem table that will
guarantee that Originators, Screeners and so forth exist in the Personnel
table, you may want to use LEFT JOINS to ensure that you get rows back.
HTH
Rick Sawtell
MCT, MCSD, MCDBA|||Thanks...that helps a lot. I forgot about using the IsNull function. It
greatly simplifies the query. One question I have since you mentioned foreig
n
keys. The personnel table is located in another database. Is there a way to
create a foreign key that will span databases? Thanks for your help.
"Rick Sawtell" wrote:

> "Mike Collins" <MikeCollins@.discussions.microsoft.com> wrote in message
> news:5C6CE19B-3FCE-422E-B546-3A1FDC7DD28B@.microsoft.com...
>
> From where I sit, you will need to do the joins. A couple of suggestions
> however.
> 1. Use ISNULL for the MiddleName column. If it is empty, you will not ge
t
> a row back because by default NULL Concatenation returns NULL. So
> something like: ISNULL(p1.FirstName, '') + ' ' + ISNULL(p1.MiddleName,
> '')...
> 2. Since I don't see any FK constraints in the Problem table that will
> guarantee that Originators, Screeners and so forth exist in the Personnel
> table, you may want to use LEFT JOINS to ensure that you get rows back.
> HTH
> Rick Sawtell
> MCT, MCSD, MCDBA
>
>|||"Mike Collins" <MikeCollins@.discussions.microsoft.com> wrote in message
news:CBAC9424-506B-40A3-85DD-8945A4AC61B5@.microsoft.com...
> Thanks...that helps a lot. I forgot about using the IsNull function. It
> greatly simplifies the query. One question I have since you mentioned
> foreign
> keys. The personnel table is located in another database. Is there a way
> to
> create a foreign key that will span databases? Thanks for your help.
>
You can't do it across DB's AFAIK. You can use sprocs and/or triggers for
this however, but it may slow your system down. Then again, you will
guarantee integrity that way. It's up to you.
Rick

ADDING WITH COUNTING

Below is my query so far. There is a field in Winpayment call
transaction_amount that I would like to add up for use count statement if
possible. So what I am asking is there a way to for each count case add the
transaction amount and have a transaction total show for each count case
statement. For example, every exsistence in the first count statement would
be added up by using the transaction_amount and then have a field right afte
r
SHEETZ_MC_TAPPED_INSIDE say transactions total? Thanks for any help.
Use Winpayment
GO
SELECT S.card_acceptor_identification STORE,
COUNT(M.card_acceptor_identification) TOTAL,
COUNT(CASE WHEN id_code_1 = 'MC' and terminal_num = '001' and pos_entry_mode
= '921' THEN 1 END) SHEETZ_MC_TAPPED_INSIDE,
COUNT(CASE WHEN id_code_1 = 'MC' and terminal_num = '001' and pos_entry_mode
= '021' THEN 1 END) SHEETZ_MC_SWIPED_INSIDE,
COUNT(CASE WHEN id_code_1 = 'MC' and terminal_num = '003' and pos_entry_mode
= '921' THEN 1 END) SHEETZ_MC_TAPPED_OUTSIDE,
COUNT(CASE WHEN id_code_1 = 'MC' and terminal_num = '003' and pos_entry_mode
= '021' THEN 1 END) SHEETZ_MC_SWIPED_OUTSIDE
FROM Store S
Left Join financial_message M
On M.card_acceptor_identification = S.card_acceptor_identification
And settlement_batch_number = '961'
AND id_number_1 like '540168%'
Where len (S.card_acceptor_identification) = 4
GROUP BY S.card_acceptor_identificationI'm not following what you are trying to do. In addition to your query,
could you post the DDL and a few rows of sample data and something showing
your expected result?
--Brian
(Please reply to the newsgroups only.)
"tarheels4025" <tarheels4025@.discussions.microsoft.com> wrote in message
news:8C71D6DF-414C-4B77-95CD-2934AB2CA45D@.microsoft.com...
> Below is my query so far. There is a field in Winpayment call
> transaction_amount that I would like to add up for use count statement if
> possible. So what I am asking is there a way to for each count case add
> the
> transaction amount and have a transaction total show for each count case
> statement. For example, every exsistence in the first count statement
> would
> be added up by using the transaction_amount and then have a field right
> after
> SHEETZ_MC_TAPPED_INSIDE say transactions total? Thanks for any help.
>
> Use Winpayment
> GO
> SELECT S.card_acceptor_identification STORE,
> COUNT(M.card_acceptor_identification) TOTAL,
> COUNT(CASE WHEN id_code_1 = 'MC' and terminal_num = '001' and
> pos_entry_mode
> = '921' THEN 1 END) SHEETZ_MC_TAPPED_INSIDE,
> COUNT(CASE WHEN id_code_1 = 'MC' and terminal_num = '001' and
> pos_entry_mode
> = '021' THEN 1 END) SHEETZ_MC_SWIPED_INSIDE,
> COUNT(CASE WHEN id_code_1 = 'MC' and terminal_num = '003' and
> pos_entry_mode
> = '921' THEN 1 END) SHEETZ_MC_TAPPED_OUTSIDE,
> COUNT(CASE WHEN id_code_1 = 'MC' and terminal_num = '003' and
> pos_entry_mode
> = '021' THEN 1 END) SHEETZ_MC_SWIPED_OUTSIDE
> FROM Store S
> Left Join financial_message M
> On M.card_acceptor_identification = S.card_acceptor_identification
> And settlement_batch_number = '961'
> AND id_number_1 like '540168%'
> Where len (S.card_acceptor_identification) = 4
> GROUP BY S.card_acceptor_identification

Thursday, March 22, 2012

Adding value in a query

I am trying to insert a value numeric + 1 in to db table but i get error when i do this

this is the code

Const SQLAsString ="INSERT INTO [PageHits] ([DefaultPage]) VALUES (@.defaultP)"

Dim myCommandAsNew Data.SqlClient.SqlCommand(SQL, myConnection)myCommand.Parameters.AddWithValue("@.DefaultP" +"1", DefaultP.Text.Trim())

myConnection.Open()

myCommand.ExecuteNonQuery()

myConnection.Close()

The Error:

Must declare the variable '@.defaultP'.

Description:An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details:System.Data.SqlClient.SqlException: Must declare the variable '@.defaultP'.

The code you wrote will send a parameter called @.DefaultP1 to the database.

Did you want to increase an existing value in the database? If so, you must use an UPDATE query.sql

Adding Users to MSDE

I am having a authentication problem.. users log into my website... I authenticate them against Active Directory.. and then I try to query a MSDE database... my connection string is as follows:


Dim connectionString As String = "server='srv_sql'; user id='sa'; password='MyPassword'; Database='MyDB'"
Dim dbConnection As System.Data.SqlClient.SqlConnection = New System.Data.SqlClient.SqlConnection(connectionString)

However since I have


<identity impersonate=true>

in my web.config file... it tries to login to the MSDE database as the user.. not as the user SA.

I cannot change the web.config file, since I need that for the active directory authentication to work...

in SQL Server you can add users to a database through the enterprise manager.. how can I do a similar thing using MSDE ?

Is it even possible? or do I have to upgrade to a full SQL instance?

any help would be appreciatedTo answer your question, use the osql command line utility. See this KB article for more info:HOW TO: Manage the SQL Server Desktop Engine (MSDE 2000) by Using the Osql Utility.

what you need to do is use the sp_grantlogin system sp to add the login:

EXEC sp_grantlogin 'Corporate\Test'

Then give it access like this:

EXEC sp_grantdbaccess 'Corporate\BobJ', 'Bob'

You'll also need to give it permissions.

That said, there may need to be adjustments for use with Active Directory.

BUT, you should never, ever, NEVER use the sa login for database access. Not for any app and certainly not for an ASP.NET app. You're opening yourself up to a whole lot of hurt doing it this way. Instead, create a login that has only the specific permissions needed to run the app. No more.

It's more work, but you'll have made the app far more secure.

Don|||...for sure don't use SA on the page itself. What about permissioning the database with Windows authenticated logins since you are using AD...if you haven't already. If you do then you can set windows authentication via Internet Services Manager on the directory hosting the page (be sure to get rid of anonymous users)

adding up values

Hello,
I have a query that returns some transactions I have to look at:
select t.tradeID, ABS(t.volume) as totalVolume, ABS(tr.volume) as
partialVolume, t.symbol
from transactions tr, trades t
where tr.tradeID = t.tradeID AND (tr.isMatched = 0 OR tr.isMatched IS NULL)
Sample Data:
tradeID totalVolume partialVolume Symbol
247 4000 2000 ABC
247 4000 1000 ABC
247 4000 500 ABC
247 4000 500 ABC
248 2000 1000 XYZ
248 2000 1500 XYZ
What I want to do is that add the particalVolume column up to give me the
values 4000 and 1500 in this case.
SO far what I have.
Create Table #tempTable
(
ID numeric
)
INSERT INTO #tempTable Select transactionID from transactions where moniker
IS NULL
declare @.partialVolume int
set @.partialVolume = 0
declare @.tempTradeID int
WHILE Exists(Select ID from #tempTable)
begin
Select @.partialVolume = (volume from transactions Where tradeID = @.tempTradeID + @.partialVolume
END
It doesn't work.For those curious.
I got this to work using the SUM function.
Here is the SQL statement.
select t.tradeID, t.symbol, tr.[transaction], t.volume, sum(tr.volume),
t.accountNumber
from transactions tr, trades t
where tr.symbol = t.symbol AND LEFT(tr.[transaction], 1) =LEFT(t.[transaction], 1) AND tr.date = t.date AND tr.moniker is NULL
group by t.tradeid, t.symbol, tr.[transaction], t.volume, t.accountNumber
"Won Lee" <noemail> wrote in message
news:%23Ytzp90aDHA.2932@.tk2msftngp13.phx.gbl...
> Hello,
> I have a query that returns some transactions I have to look at:
> select t.tradeID, ABS(t.volume) as totalVolume, ABS(tr.volume) as
> partialVolume, t.symbol
> from transactions tr, trades t
> where tr.tradeID = t.tradeID AND (tr.isMatched = 0 OR tr.isMatched IS
NULL)
> Sample Data:
> tradeID totalVolume partialVolume Symbol
> 247 4000 2000 ABC
> 247 4000 1000 ABC
> 247 4000 500 ABC
> 247 4000 500 ABC
> 248 2000 1000 XYZ
> 248 2000 1500 XYZ
>
> What I want to do is that add the particalVolume column up to give me the
> values 4000 and 1500 in this case.
> SO far what I have.
> Create Table #tempTable
> (
> ID numeric
> )
> INSERT INTO #tempTable Select transactionID from transactions where
moniker
> IS NULL
> declare @.partialVolume int
> set @.partialVolume = 0
> declare @.tempTradeID int
> WHILE Exists(Select ID from #tempTable)
> begin
> Select @.partialVolume = (volume from transactions Where tradeID => @.tempTradeID + @.partialVolume
>
> END
> It doesn't work.
>

Adding Unique data

Dear Folks,
I have a table like
Invno Amount
55 100
55 200
56 50
57 150
57 300
57 50
I need to query to make it as
55 - 300
56 - 50
57 - 500
Please help me...
Thanks for your replies in advance.
Regards,
Selvarathinam.SELECT InvNo, SUM(Amount)
FROM Table
GROUP BY InvNo
Selvarathinam wrote:
> Dear Folks,
> I have a table like
> Invno Amount
> 55 100
> 55 200
> 56 50
> 57 150
> 57 300
> 57 50
> I need to query to make it as
> 55 - 300
> 56 - 50
> 57 - 500
> Please help me...
> Thanks for your replies in advance.
> Regards,
> Selvarathinam.|||Select invno, sum(amount) group by invno
"Selvarathinam" <s.selvarathinam@.gmail.com> wrote in message
news:1149799832.127814.236410@.y43g2000cwc.googlegroups.com...
> Dear Folks,
> I have a table like
> Invno Amount
> 55 100
> 55 200
> 56 50
> 57 150
> 57 300
> 57 50
> I need to query to make it as
> 55 - 300
> 56 - 50
> 57 - 500
> Please help me...
> Thanks for your replies in advance.
> Regards,
> Selvarathinam.
>|||Thanks a ton...
itz working
Tracy McKibben wrote:
> SELECT InvNo, SUM(Amount)
> FROM Table
> GROUP BY InvNo
>
> Selvarathinam wrote:

Adding two dates

I have two fields, Date Purchased (smalldatetime) and warranty in months (integer).

can anyone help me to formulate a query to show the date when the warranty ends, and/or the remaining days/months in the warranty please?

I'm not sure if its doable, but i would really appreciate it if anyone can help me!

Give a look to the DATEADD function in books online; it looks like this:

declare @.example table
( rid integer,
datePurchased smalldatetime,
warranty integer
)

insert into @.example
select 1, '4/8/7', 3 union all
select 2, '5/14/7', 12

select rid,
convert(varchar(10), datePurchased, 101) as datePurchased,
warranty,
dateadd (mm, warranty, datePurchased) as warrantyEndDate,
datediff (day, getdate(), dateadd (mm, warranty, datePurchased)) as daysRemaining,
datediff (mm, getdate(), dateadd (mm, warranty, datePurchased)) as monthsRemaining
from @.example

/*
rid datePurchased warranty warrantyEndDate daysRemaining monthsRemaining
-- - -- - -
1 04/08/2007 3 2007-07-08 00:00:00 45 2
2 05/14/2007 12 2008-05-14 00:00:00 356 12
*/

Tuesday, March 20, 2012

adding text to the column data in a query result

If I had a table with 3 columns in it, named "ID", "TITLE" and "CLASS_ID" and, in a query result, I wanted to add a fourth column named "URL" that would be the result of concatenating a file name and the value in "ID", how would I do that?

so a table that looked like:
ID TITLE CLASS_ID
1 "Hello" 137
3 "Goodbye" 587
19 "Whatever" 1028

could return a result set that looked like:
ID TITLE CLASS_ID URL

1 "Hello" 137 "hardcodedfilename.aspx?id=1"

3 "Goodbye" 587 "hardcodedfilename.aspx?id=3"

19 "Whatever" 1028 "hardcodedfilename.aspx?id=19"

I have looked through my SQL book, and scanned the usual help files and google search options, but I haven't seen an example of this. Can it be done, and if so, how?

Thanks in advance for your help.
roger

There are a few approaches, two different ways are shown below.

Chris

DECLARE @.URLTemplate VARCHAR(100)

SET @.URLTemplate = '"hardcodedfilename.aspx?id=**"'

SELECT ID,

TITLE,

CLASS_ID,

REPLACE(@.URLTemplate, '**', CAST(ID AS VARCHAR(10))) AS URL

FROM ...

--or

DECLARE @.prefix VARCHAR(100)

SET @.prefix = '"hardcodedfilename.aspx?id='

SELECT ID,

TITLE,

CLASS_ID,

@.prefix + CAST(ID AS VARCHAR(10)) + '"' AS URL

FROM ...

|||Thank you for your quick response!
I inserted the code you suggested into my existing, recursive function. The original function (which does work as it is) is:
ALTER FUNCTION [dbo].[fn_WPMTREE](@.SceneID int)
RETURNS XML
WITH RETURNS NULL ON NULL INPUT
BEGIN RETURN

SET @.prefix = "rightframe.aspx?s="
(SELECT ID As "@.id", TITLE as "@.title", CLASS_ID as "@.clsID",
CASE WHEN PARENT_ID=@.SceneID
THEN dbo.fn_WPMTREE(id)
END
FROM dbo.SCENE WHERE PARENT_ID=@.SceneID
FOR XML PATH('Scene'), TYPE)
END

now, it looks like:
ALTER FUNCTION [dbo].[fn_WPMTREE](@.SceneID int)
RETURNS XML
WITH RETURNS NULL ON NULL INPUT
BEGIN RETURN XML

DECLARE @.prefix VARCHAR(100)
SET @.prefix = "rightframe.aspx?s="
(SELECT ID As "@.id", TITLE as "@.title", CLASS_ID as "@.clsID", @.prefix + CAST(ID AS VARCHAR(10)) + " " as "@.url",
CASE WHEN PARENT_ID=@.SceneID
THEN dbo.fn_WPMTREE(id)
END
FROM dbo.SCENE WHERE PARENT_ID=@.SceneID
FOR XML PATH('Scene'), TYPE)
END

But, I get an error:
Msg 156, Level 15, State 1, Procedure fn_WPMTREE, Line 18
Incorrect syntax near the keyword 'FOR'.

Any suggestions? And thanks again for your help.|||

I've made a couple of corrections, see the example below.

I wasn't sure whether you needed the trailing space in the following:

CAST(ID AS VARCHAR(10)) + ' ' as "@.url",

If not, then simply replace the above with the following:

CAST(ID AS VARCHAR(10)) as "@.url",

Chris

CREATE FUNCTION [dbo].[fn_WPMTREE](@.SceneID int)

RETURNS XML

WITH RETURNS NULL ON NULL INPUT

BEGIN

DECLARE @.prefix VARCHAR(100)

SET @.prefix = 'rightframe.aspx?s='

RETURN (

SELECT ID As "@.id", TITLE as "@.title", CLASS_ID as "@.clsID", @.prefix + CAST(ID AS VARCHAR(10)) + ' ' as "@.url",

CASE WHEN PARENT_ID=@.SceneID

THEN dbo.fn_WPMTREE(id)

END

FROM dbo.SCENE WHERE PARENT_ID=@.SceneID

FOR XML PATH('Scene'), TYPE

)

END

|||That works beautifully!

I can't thank you enough.

Now, all I have to do is get an INNER JOIN working in this, and I am in good shape!

Again, Thank you.|||

HI Chris,

I have a similar question. I have a query that I use for a letter that I create. I'm attaching the query below. I want to add the text "CRM" next to the output result for "AgentDesc". So if the output of "AgentDesc" is "Director"; then I want it to display as CRM Director. Am sure this is easy enough for you..:

Thanks

SELECT dbo.tblOffer.*, CRM_SQL_ADMIN.DtFormat(dbo.tblOffer.OfferDt, 'mm dd, yyyy') AS OfferDate, LTRIM(CRM_SQL_ADMIN.NZ(dbo.l_tblBusAnalyst.FName)
+ ' ' + CRM_SQL_ADMIN.NZ(dbo.l_tblBusAnalyst.LName)) AS AnalName, LTRIM(CRM_SQL_ADMIN.NZ(dbo.l_tblAgent.FName)
+ ' ' + CRM_SQL_ADMIN.NZ(dbo.l_tblAgent.LName)) AS AgentName, dbo.l_tblAgent.AgentDesc AS AgentDesc,
CRM_SQL_ADMIN.vwOfferAgent_Names.DCAName AS DCAName, CRM_SQL_ADMIN.vwOfferAgent_Names.MCAName AS MCAName,
CRM_SQL_ADMIN.vwOfferAgent_Names.DIRName AS DIRName, CRM_SQL_ADMIN.vwOfferAgent_Names.RMName AS RMName,
CRM_SQL_ADMIN.vwOfferAgent_Names.SReps AS SReps,
(SELECT Description
FROM l_tbl_Options
WHERE [Field] = 'PayTerms' AND [OPTION] = [tblOffer].[PayTerms]) AS PayTerms_Desc, dbo.l_tblCust.CustName AS CustName,
dbo.l_tblCust.StAddress AS StAddress, dbo.l_tblCust.City AS City, dbo.l_tblCust.State AS State, dbo.l_tblCust.ZipCode AS ZipCode,
dbo.l_tblCust.GPO AS GPO, dbo.l_tblCust.IsTargetCust AS IsTargetCust,
(SELECT Description
FROM l_tbl_Options
WHERE [Field] = 'ProgBen' AND CONVERT(bit, [OPTION]) = [tblOffer].[ProgBen]) AS ProgBen_Desc,
(SELECT Description
FROM l_tbl_Options
WHERE [Field] = 'ProgCrit' AND CONVERT(bit, [OPTION]) = [tblOffer].[ProgCrit]) AS ProgCrit_Desc, dbo.tblOffer.SpecProgType AS SpecProg,
CRM_SQL_ADMIN.DtFormat(CRM_SQL_ADMIN.EndOfQtr(dbo.tblOffer.OfferDt), 'mm dd, yyyy') AS EndOfQtr,
CRM_SQL_ADMIN.DtFormat(CRM_SQL_ADMIN.WeekDayAdd(- 4, CRM_SQL_ADMIN.EndOfQtr(dbo.tblOffer.OfferDt)), 'mm dd, yyyy') AS EndOfQtrLess3d,
OSS.Tot_Qty AS Tot_Qty, CRM_SQL_ADMIN.GetUSDNo00(OSS.Tot_Purch) AS Tot_Purch, CRM_SQL_ADMIN.GetUSDNo00(OSS.Tot_Savings)
AS Tot_Savings
FROM dbo.l_tblCust INNER JOIN
dbo.tblOffer ON dbo.l_tblCust.CustNum = dbo.tblOffer.CustNum LEFT OUTER JOIN
dbo.l_tblBusAnalyst ON dbo.tblOffer.BusAnalystID = dbo.l_tblBusAnalyst.EmpNum LEFT OUTER JOIN
CRM_SQL_ADMIN.vwOfferAgent_Names ON dbo.tblOffer.OfferID = CRM_SQL_ADMIN.vwOfferAgent_Names.OfferID LEFT OUTER JOIN
dbo.l_tblAgent ON dbo.tblOffer.AgentID = dbo.l_tblAgent.AgentID INNER JOIN
CRM_SQL_ADMIN.vwOfferSums_Simple OSS ON dbo.tblOffer.OfferID = OSS.OfferID|||

Change:

dbo.l_tblAgent.AgentDesc AS AgentDesc,

to:

( 'CRM ' + dbo.l_tblAgent.AgentDesc ) AS AgentDesc,

|||Gr8...That works...Thanks a lot Arnie for your help...

adding text to the column data in a query result

If I had a table with 3 columns in it, named "ID", "TITLE" and "CLASS_ID" and, in a query result, I wanted to add a fourth column named "URL" that would be the result of concatenating a file name and the value in "ID", how would I do that?

so a table that looked like:
ID TITLE CLASS_ID
1 "Hello" 137
3 "Goodbye" 587
19 "Whatever" 1028

could return a result set that looked like:
ID TITLE CLASS_ID URL
1 "Hello" 137 "hardcodedfilename.aspx?id=1"
3 "Goodbye" 587 "hardcodedfilename.aspx?id=3"
19 "Whatever" 1028 "hardcodedfilename.aspx?id=19"

I have looked through my SQL book, and scanned the usual help files and google search options, but I haven't seen an example of this. Can it be done, and if so, how?

Thanks in advance for your help.
roger

There are a few approaches, two different ways are shown below.

Chris

DECLARE @.URLTemplate VARCHAR(100)

SET @.URLTemplate = '"hardcodedfilename.aspx?id=**"'

SELECT ID,

TITLE,

CLASS_ID,

REPLACE(@.URLTemplate, '**', CAST(ID AS VARCHAR(10))) AS URL

FROM ...

--or

DECLARE @.prefix VARCHAR(100)

SET @.prefix = '"hardcodedfilename.aspx?id='

SELECT ID,

TITLE,

CLASS_ID,

@.prefix + CAST(ID AS VARCHAR(10)) + '"' AS URL

FROM ...

|||Thank you for your quick response!
I inserted the code you suggested into my existing, recursive function. The original function (which does work as it is) is:
ALTER FUNCTION [dbo].[fn_WPMTREE](@.SceneID int)
RETURNS XML
WITH RETURNS NULL ON NULL INPUT
BEGIN RETURN

SET @.prefix = "rightframe.aspx?s="
(SELECT ID As "@.id", TITLE as "@.title", CLASS_ID as "@.clsID",
CASE WHEN PARENT_ID=@.SceneID
THEN dbo.fn_WPMTREE(id)
END
FROM dbo.SCENE WHERE PARENT_ID=@.SceneID
FOR XML PATH('Scene'), TYPE)
END

now, it looks like:
ALTER FUNCTION [dbo].[fn_WPMTREE](@.SceneID int)
RETURNS XML
WITH RETURNS NULL ON NULL INPUT
BEGIN RETURN XML

DECLARE @.prefix VARCHAR(100)
SET @.prefix = "rightframe.aspx?s="
(SELECT ID As "@.id", TITLE as "@.title", CLASS_ID as "@.clsID", @.prefix + CAST(ID AS VARCHAR(10)) + " " as "@.url",
CASE WHEN PARENT_ID=@.SceneID
THEN dbo.fn_WPMTREE(id)
END
FROM dbo.SCENE WHERE PARENT_ID=@.SceneID
FOR XML PATH('Scene'), TYPE)
END

But, I get an error:
Msg 156, Level 15, State 1, Procedure fn_WPMTREE, Line 18
Incorrect syntax near the keyword 'FOR'.

Any suggestions? And thanks again for your help.

|||

I've made a couple of corrections, see the example below.

I wasn't sure whether you needed the trailing space in the following:

CAST(ID AS VARCHAR(10)) + ' ' as "@.url",

If not, then simply replace the above with the following:

CAST(ID AS VARCHAR(10)) as "@.url",

Chris

CREATE FUNCTION [dbo].[fn_WPMTREE](@.SceneID int)

RETURNS XML

WITH RETURNS NULL ON NULL INPUT

BEGIN

DECLARE @.prefix VARCHAR(100)

SET @.prefix = 'rightframe.aspx?s='

RETURN (

SELECT ID As "@.id", TITLE as "@.title", CLASS_ID as "@.clsID", @.prefix + CAST(ID AS VARCHAR(10)) + ' ' as "@.url",

CASE WHEN PARENT_ID=@.SceneID

THEN dbo.fn_WPMTREE(id)

END

FROM dbo.SCENE WHERE PARENT_ID=@.SceneID

FOR XML PATH('Scene'), TYPE

)

END

|||That works beautifully!

I can't thank you enough.

Now, all I have to do is get an INNER JOIN working in this, and I am in good shape!

Again, Thank you.
|||

HI Chris,

I have a similar question. I have a query that I use for a letter that I create. I'm attaching the query below. I want to add the text "CRM" next to the output result for "AgentDesc". So if the output of "AgentDesc" is "Director"; then I want it to display as CRM Director. Am sure this is easy enough for you..:

Thanks

SELECT dbo.tblOffer.*, CRM_SQL_ADMIN.DtFormat(dbo.tblOffer.OfferDt, 'mm dd, yyyy') AS OfferDate, LTRIM(CRM_SQL_ADMIN.NZ(dbo.l_tblBusAnalyst.FName)
+ ' ' + CRM_SQL_ADMIN.NZ(dbo.l_tblBusAnalyst.LName)) AS AnalName, LTRIM(CRM_SQL_ADMIN.NZ(dbo.l_tblAgent.FName)
+ ' ' + CRM_SQL_ADMIN.NZ(dbo.l_tblAgent.LName)) AS AgentName, dbo.l_tblAgent.AgentDesc AS AgentDesc,
CRM_SQL_ADMIN.vwOfferAgent_Names.DCAName AS DCAName, CRM_SQL_ADMIN.vwOfferAgent_Names.MCAName AS MCAName,
CRM_SQL_ADMIN.vwOfferAgent_Names.DIRName AS DIRName, CRM_SQL_ADMIN.vwOfferAgent_Names.RMName AS RMName,
CRM_SQL_ADMIN.vwOfferAgent_Names.SReps AS SReps,
(SELECT Description
FROM l_tbl_Options
WHERE [Field] = 'PayTerms' AND [OPTION] = [tblOffer].[PayTerms]) AS PayTerms_Desc, dbo.l_tblCust.CustName AS CustName,
dbo.l_tblCust.StAddress AS StAddress, dbo.l_tblCust.City AS City, dbo.l_tblCust.State AS State, dbo.l_tblCust.ZipCode AS ZipCode,
dbo.l_tblCust.GPO AS GPO, dbo.l_tblCust.IsTargetCust AS IsTargetCust,
(SELECT Description
FROM l_tbl_Options
WHERE [Field] = 'ProgBen' AND CONVERT(bit, [OPTION]) = [tblOffer].[ProgBen]) AS ProgBen_Desc,
(SELECT Description
FROM l_tbl_Options
WHERE [Field] = 'ProgCrit' AND CONVERT(bit, [OPTION]) = [tblOffer].[ProgCrit]) AS ProgCrit_Desc, dbo.tblOffer.SpecProgType AS SpecProg,
CRM_SQL_ADMIN.DtFormat(CRM_SQL_ADMIN.EndOfQtr(dbo.tblOffer.OfferDt), 'mm dd, yyyy') AS EndOfQtr,
CRM_SQL_ADMIN.DtFormat(CRM_SQL_ADMIN.WeekDayAdd(- 4, CRM_SQL_ADMIN.EndOfQtr(dbo.tblOffer.OfferDt)), 'mm dd, yyyy') AS EndOfQtrLess3d,
OSS.Tot_Qty AS Tot_Qty, CRM_SQL_ADMIN.GetUSDNo00(OSS.Tot_Purch) AS Tot_Purch, CRM_SQL_ADMIN.GetUSDNo00(OSS.Tot_Savings)
AS Tot_Savings
FROM dbo.l_tblCust INNER JOIN
dbo.tblOffer ON dbo.l_tblCust.CustNum = dbo.tblOffer.CustNum LEFT OUTER JOIN
dbo.l_tblBusAnalyst ON dbo.tblOffer.BusAnalystID = dbo.l_tblBusAnalyst.EmpNum LEFT OUTER JOIN
CRM_SQL_ADMIN.vwOfferAgent_Names ON dbo.tblOffer.OfferID = CRM_SQL_ADMIN.vwOfferAgent_Names.OfferID LEFT OUTER JOIN
dbo.l_tblAgent ON dbo.tblOffer.AgentID = dbo.l_tblAgent.AgentID INNER JOIN
CRM_SQL_ADMIN.vwOfferSums_Simple OSS ON dbo.tblOffer.OfferID = OSS.OfferID|||

Change:

dbo.l_tblAgent.AgentDesc AS AgentDesc,

to:

( 'CRM ' + dbo.l_tblAgent.AgentDesc ) AS AgentDesc,

|||Gr8...That works...Thanks a lot Arnie for your help...sql

Monday, March 19, 2012

Adding staggered running total and average to query

Hi,

I am trying to add a staggered running total and average to a query
returning quarterly CPI data. I need to add 4 quarterly data points
together to calculate a moving 12-month sum (YrCPI), and then to
complicate things, calculate a moving average of the 12-month figure
(AvgYrCPI).

Given the sample data:

CREATE TABLE [dbo].[QtrInflation] (
[Qtr] [smalldatetime] NOT NULL ,
[CPI] [decimal](8, 4) NOT NULL
) ON [PRIMARY]
GO

INSERT INTO QtrInflation (Qtr, CPI)
SELECT '1960-03-01', 0.7500 UNION
SELECT '1960-06-01', 1.4800 UNION
SELECT '1960-09-01', 1.4600 UNION
SELECT '1960-12-01', 0.7200 UNION
SELECT '1961-03-01', 0.7100 UNION
SELECT '1961-06-01', 0.7100 UNION
SELECT '1961-09-01',-0.7000 UNION
SELECT '1961-12-01', 0.0000 UNION
SELECT '1962-03-01', 0.0000 UNION
SELECT '1962-06-01', 0.0000 UNION
SELECT '1962-09-01', 0.0000 UNION
SELECT '1962-12-01', 0.0000 UNION
SELECT '1963-03-01', 0.0000 UNION
SELECT '1963-06-01', 0.0000 UNION
SELECT '1963-09-01', 0.7100 UNION
SELECT '1963-12-01', 0.0000 UNION
SELECT '1964-03-01', 0.7000 UNION
SELECT '1964-06-01', 0.7000 UNION
SELECT '1964-09-01', 1.3900 UNION
SELECT '1964-12-01', 0.6800 UNION
SELECT '1965-03-01', 0.6800 UNION
SELECT '1965-06-01', 1.3500 UNION
SELECT '1965-09-01', 0.6700 UNION
SELECT '1965-12-01', 1.3200

I am trying to return the following results:

Qtr CPI YrCPI AvgYrCPI
--- -- -- ---
1-Jun-60 1.48
1-Sep-60 1.46
1-Dec-60 0.72
1-Mar-61 0.71 4.37
1-Jun-61 0.71 3.60
1-Sep-61 -0.70 1.44
1-Dec-61 0.00 0.72 2.53
1-Mar-62 0.00 0.01 1.44
1-Jun-62 0.00 -0.70 0.37
1-Sep-62 0.00 0.00 0.01
1-Dec-62 0.00 0.00 -0.17
1-Mar-63 0.00 0.00 -0.18
1-Jun-63 0.00 0.00 0.00
1-Sep-63 0.71 0.71 0.18
1-Dec-63 0.00 0.71 0.36
1-Mar-64 0.70 1.41 0.71
1-Jun-64 0.70 2.11 1.24
1-Sep-64 1.39 2.79 1.76
1-Dec-64 0.68 3.47 2.45
1-Mar-65 0.68 3.45 2.96
1-Jun-65 1.35 4.10 3.45
1-Sep-65 0.67 3.38 3.60
1-Dec-65 1.32 4.02 3.74

Note, 4 data points are required to calculate a moving sum of CPI
(YrCPI) and 4 calculate YrCPI figures are required calculate the
annual average of YrCPI (AvgYrCPI), giving a staggered effect to the
first 7 results

This sad effort is about as far as I've got:

SELECT I.Qtr, I.CPI, SUM(S.CPI) AS YrCPI
FROM QtrInflation I
JOIN (
SELECT TOP 4 Qtr, CPI
FROM QtrInflation
) S
ON S.Qtr <= I.Qtr
GROUP BY I.Qtr, I.CPI
ORDER BY I.Qtr ASC

Can anyone suggest how do achieve this result without having to resort
to cursors?

Thanks,

StephenHi

This will do it (I think!) but there may be a neater way!

SELECT S.Qtr, S.CPI, D.YrCPI, E.AvgCPI
FROM QtrInflation S LEFT JOIN
( SELECT Q.Qtr, SUM(A.CPI) AS YrCPI
FROM QtrInflation Q LEFT JOIN ( SELECT Qtr, SUM(CPI) AS CPI
FROM QtrInflation
GROUP BY Qtr) A ON Q.Qtr >= A.Qtr AND DATEADD(YEAR,-1,Q.Qtr) < A.Qtr
GROUP BY Q.Qtr
HAVING COUNT(A.Qtr) = 4 ) D ON S.Qtr = D.Qtr
LEFT JOIN
( SELECT R.Qtr, SUM(B.CPI)/4 AS AvgCPI
FROM QtrInflation R LEFT JOIN ( SELECT Q.Qtr, SUM(A.CPI) AS CPI
FROM QtrInflation Q LEFT JOIN ( SELECT Qtr, SUM(CPI) AS CPI
FROM QtrInflation
GROUP BY Qtr) A ON Q.Qtr >= A.Qtr AND DATEADD(YEAR,-1,Q.Qtr) < A.Qtr
GROUP BY Q.Qtr
HAVING COUNT(A.Qtr) = 4 ) B ON R.Qtr >= B.Qtr AND DATEADD(YEAR,-1,R.Qtr)
< B.Qtr
GROUP BY R.Qtr
HAVING COUNT(B.Qtr) = 4 ) E ON S.Qtr = E.Qtr
ORDER BY S.Qtr

John
"Stephen Miller" <jsausten@.hotmail.com> wrote in message
news:cdb404de.0309210139.58ffad34@.posting.google.c om...
> Hi,
> I am trying to add a staggered running total and average to a query
> returning quarterly CPI data. I need to add 4 quarterly data points
> together to calculate a moving 12-month sum (YrCPI), and then to
> complicate things, calculate a moving average of the 12-month figure
> (AvgYrCPI).
> Given the sample data:
> CREATE TABLE [dbo].[QtrInflation] (
> [Qtr] [smalldatetime] NOT NULL ,
> [CPI] [decimal](8, 4) NOT NULL
> ) ON [PRIMARY]
> GO
> INSERT INTO QtrInflation (Qtr, CPI)
> SELECT '1960-03-01', 0.7500 UNION
> SELECT '1960-06-01', 1.4800 UNION
> SELECT '1960-09-01', 1.4600 UNION
> SELECT '1960-12-01', 0.7200 UNION
> SELECT '1961-03-01', 0.7100 UNION
> SELECT '1961-06-01', 0.7100 UNION
> SELECT '1961-09-01',-0.7000 UNION
> SELECT '1961-12-01', 0.0000 UNION
> SELECT '1962-03-01', 0.0000 UNION
> SELECT '1962-06-01', 0.0000 UNION
> SELECT '1962-09-01', 0.0000 UNION
> SELECT '1962-12-01', 0.0000 UNION
> SELECT '1963-03-01', 0.0000 UNION
> SELECT '1963-06-01', 0.0000 UNION
> SELECT '1963-09-01', 0.7100 UNION
> SELECT '1963-12-01', 0.0000 UNION
> SELECT '1964-03-01', 0.7000 UNION
> SELECT '1964-06-01', 0.7000 UNION
> SELECT '1964-09-01', 1.3900 UNION
> SELECT '1964-12-01', 0.6800 UNION
> SELECT '1965-03-01', 0.6800 UNION
> SELECT '1965-06-01', 1.3500 UNION
> SELECT '1965-09-01', 0.6700 UNION
> SELECT '1965-12-01', 1.3200
>
> I am trying to return the following results:
> Qtr CPI YrCPI AvgYrCPI
> --- -- -- ---
> 1-Jun-60 1.48
> 1-Sep-60 1.46
> 1-Dec-60 0.72
> 1-Mar-61 0.71 4.37
> 1-Jun-61 0.71 3.60
> 1-Sep-61 -0.70 1.44
> 1-Dec-61 0.00 0.72 2.53
> 1-Mar-62 0.00 0.01 1.44
> 1-Jun-62 0.00 -0.70 0.37
> 1-Sep-62 0.00 0.00 0.01
> 1-Dec-62 0.00 0.00 -0.17
> 1-Mar-63 0.00 0.00 -0.18
> 1-Jun-63 0.00 0.00 0.00
> 1-Sep-63 0.71 0.71 0.18
> 1-Dec-63 0.00 0.71 0.36
> 1-Mar-64 0.70 1.41 0.71
> 1-Jun-64 0.70 2.11 1.24
> 1-Sep-64 1.39 2.79 1.76
> 1-Dec-64 0.68 3.47 2.45
> 1-Mar-65 0.68 3.45 2.96
> 1-Jun-65 1.35 4.10 3.45
> 1-Sep-65 0.67 3.38 3.60
> 1-Dec-65 1.32 4.02 3.74
> Note, 4 data points are required to calculate a moving sum of CPI
> (YrCPI) and 4 calculate YrCPI figures are required calculate the
> annual average of YrCPI (AvgYrCPI), giving a staggered effect to the
> first 7 results
> This sad effort is about as far as I've got:
> SELECT I.Qtr, I.CPI, SUM(S.CPI) AS YrCPI
> FROM QtrInflation I
> JOIN (
> SELECT TOP 4 Qtr, CPI
> FROM QtrInflation
> ) S
> ON S.Qtr <= I.Qtr
> GROUP BY I.Qtr, I.CPI
> ORDER BY I.Qtr ASC
> Can anyone suggest how do achieve this result without having to resort
> to cursors?
> Thanks,
> Stephen|||Stephen,

Here is another approach that I think will work
for you:

-- alternate solution
create table Weights (
offset int,
weight decimal(3,2),
weightA decimal(3,2),
weightB decimal(3,2)
)
go

insert into Weights

select 6, 0, 0, 0.25 union all
select 5, 0, 0, 0.5 union all
select 4, 0, 0, 0.75 union all
select 3, 0, 1, 1.00 union all
select 2, 0, 1, 0.75 union all
select 1, 0, 1, 0.5 union all
select 0, 1, 1, 0.25
go

select
dateadd(month,3*Offset,Q1.Qtr) Qtr,
sum(Weight*Q1.CPI) CPI,
case when sum(WeightA) = 4 then sum(WeightA*Q1.CPI) else NULL end as YrCPI,
case when sum(WeightB) = 4 then sum(WeightB*Q1.CPI) else NULL end as MACPI
from QtrInflation Q1, Weights
group by dateadd(month,3*Offset,Q1.Qtr)
having sum(Weight) = 1
order by dateadd(month,3*Offset,Q1.Qtr)

-- Steve Kass
-- Drew University
-- Ref: 17F9A22A-8DDA-4812-A8CD-B68062BADFA1

Stephen Miller wrote:
> Hi,
> I am trying to add a staggered running total and average to a query
> returning quarterly CPI data. I need to add 4 quarterly data points
> together to calculate a moving 12-month sum (YrCPI), and then to
> complicate things, calculate a moving average of the 12-month figure
> (AvgYrCPI).
> Given the sample data:
> CREATE TABLE [dbo].[QtrInflation] (
> [Qtr] [smalldatetime] NOT NULL ,
> [CPI] [decimal](8, 4) NOT NULL
> ) ON [PRIMARY]
> GO
> INSERT INTO QtrInflation (Qtr, CPI)
> SELECT '1960-03-01', 0.7500 UNION
> SELECT '1960-06-01', 1.4800 UNION
> SELECT '1960-09-01', 1.4600 UNION
> SELECT '1960-12-01', 0.7200 UNION
> SELECT '1961-03-01', 0.7100 UNION
> SELECT '1961-06-01', 0.7100 UNION
> SELECT '1961-09-01',-0.7000 UNION
> SELECT '1961-12-01', 0.0000 UNION
> SELECT '1962-03-01', 0.0000 UNION
> SELECT '1962-06-01', 0.0000 UNION
> SELECT '1962-09-01', 0.0000 UNION
> SELECT '1962-12-01', 0.0000 UNION
> SELECT '1963-03-01', 0.0000 UNION
> SELECT '1963-06-01', 0.0000 UNION
> SELECT '1963-09-01', 0.7100 UNION
> SELECT '1963-12-01', 0.0000 UNION
> SELECT '1964-03-01', 0.7000 UNION
> SELECT '1964-06-01', 0.7000 UNION
> SELECT '1964-09-01', 1.3900 UNION
> SELECT '1964-12-01', 0.6800 UNION
> SELECT '1965-03-01', 0.6800 UNION
> SELECT '1965-06-01', 1.3500 UNION
> SELECT '1965-09-01', 0.6700 UNION
> SELECT '1965-12-01', 1.3200
>
> I am trying to return the following results:
> Qtr CPI YrCPI AvgYrCPI
> --- -- -- ---
> 1-Jun-60 1.48
> 1-Sep-60 1.46
> 1-Dec-60 0.72
> 1-Mar-61 0.71 4.37
> 1-Jun-61 0.71 3.60
> 1-Sep-61 -0.70 1.44
> 1-Dec-61 0.00 0.72 2.53
> 1-Mar-62 0.00 0.01 1.44
> 1-Jun-62 0.00 -0.70 0.37
> 1-Sep-62 0.00 0.00 0.01
> 1-Dec-62 0.00 0.00 -0.17
> 1-Mar-63 0.00 0.00 -0.18
> 1-Jun-63 0.00 0.00 0.00
> 1-Sep-63 0.71 0.71 0.18
> 1-Dec-63 0.00 0.71 0.36
> 1-Mar-64 0.70 1.41 0.71
> 1-Jun-64 0.70 2.11 1.24
> 1-Sep-64 1.39 2.79 1.76
> 1-Dec-64 0.68 3.47 2.45
> 1-Mar-65 0.68 3.45 2.96
> 1-Jun-65 1.35 4.10 3.45
> 1-Sep-65 0.67 3.38 3.60
> 1-Dec-65 1.32 4.02 3.74
> Note, 4 data points are required to calculate a moving sum of CPI
> (YrCPI) and 4 calculate YrCPI figures are required calculate the
> annual average of YrCPI (AvgYrCPI), giving a staggered effect to the
> first 7 results
> This sad effort is about as far as I've got:
> SELECT I.Qtr, I.CPI, SUM(S.CPI) AS YrCPI
> FROM QtrInflation I
> JOIN (
> SELECT TOP 4 Qtr, CPI
> FROM QtrInflation
> ) S
> ON S.Qtr <= I.Qtr
> GROUP BY I.Qtr, I.CPI
> ORDER BY I.Qtr ASC
> Can anyone suggest how do achieve this result without having to resort
> to cursors?
> Thanks,
> Stephen|||John & Steve

Thank you for two very interesting (and very different) responses. You
guys are gurus! Both return the results I'm looking for and now I'm
stuck picking which one's best ;)

Thanks again,

Stephen

"John Bell" <jbellnewsposts@.hotmail.com> wrote in message news:<3f6d878f$0$10783$afc38c87@.news.easynet.co.uk>...
> Hi
> This will do it (I think!) but there may be a neater way!
> SELECT S.Qtr, S.CPI, D.YrCPI, E.AvgCPI
> FROM QtrInflation S LEFT JOIN
> ( SELECT Q.Qtr, SUM(A.CPI) AS YrCPI
> FROM QtrInflation Q LEFT JOIN ( SELECT Qtr, SUM(CPI) AS CPI
> FROM QtrInflation
> GROUP BY Qtr) A ON Q.Qtr >= A.Qtr AND DATEADD(YEAR,-1,Q.Qtr) < A.Qtr
> GROUP BY Q.Qtr
> HAVING COUNT(A.Qtr) = 4 ) D ON S.Qtr = D.Qtr
> LEFT JOIN
> ( SELECT R.Qtr, SUM(B.CPI)/4 AS AvgCPI
> FROM QtrInflation R LEFT JOIN ( SELECT Q.Qtr, SUM(A.CPI) AS CPI
> FROM QtrInflation Q LEFT JOIN ( SELECT Qtr, SUM(CPI) AS CPI
> FROM QtrInflation
> GROUP BY Qtr) A ON Q.Qtr >= A.Qtr AND DATEADD(YEAR,-1,Q.Qtr) < A.Qtr
> GROUP BY Q.Qtr
> HAVING COUNT(A.Qtr) = 4 ) B ON R.Qtr >= B.Qtr AND DATEADD(YEAR,-1,R.Qtr)
> < B.Qtr
> GROUP BY R.Qtr
> HAVING COUNT(B.Qtr) = 4 ) E ON S.Qtr = E.Qtr
> ORDER BY S.Qtr
> John
> "Stephen Miller" <jsausten@.hotmail.com> wrote in message
> news:cdb404de.0309210139.58ffad34@.posting.google.c om...
> > Hi,
> > I am trying to add a staggered running total and average to a query
> > returning quarterly CPI data. I need to add 4 quarterly data points
> > together to calculate a moving 12-month sum (YrCPI), and then to
> > complicate things, calculate a moving average of the 12-month figure
> > (AvgYrCPI).
> > Given the sample data:
> > CREATE TABLE [dbo].[QtrInflation] (
> > [Qtr] [smalldatetime] NOT NULL ,
> > [CPI] [decimal](8, 4) NOT NULL
> > ) ON [PRIMARY]
> > GO
> > INSERT INTO QtrInflation (Qtr, CPI)
> > SELECT '1960-03-01', 0.7500 UNION
> > SELECT '1960-06-01', 1.4800 UNION
> > SELECT '1960-09-01', 1.4600 UNION
> > SELECT '1960-12-01', 0.7200 UNION
> > SELECT '1961-03-01', 0.7100 UNION
> > SELECT '1961-06-01', 0.7100 UNION
> > SELECT '1961-09-01',-0.7000 UNION
> > SELECT '1961-12-01', 0.0000 UNION
> > SELECT '1962-03-01', 0.0000 UNION
> > SELECT '1962-06-01', 0.0000 UNION
> > SELECT '1962-09-01', 0.0000 UNION
> > SELECT '1962-12-01', 0.0000 UNION
> > SELECT '1963-03-01', 0.0000 UNION
> > SELECT '1963-06-01', 0.0000 UNION
> > SELECT '1963-09-01', 0.7100 UNION
> > SELECT '1963-12-01', 0.0000 UNION
> > SELECT '1964-03-01', 0.7000 UNION
> > SELECT '1964-06-01', 0.7000 UNION
> > SELECT '1964-09-01', 1.3900 UNION
> > SELECT '1964-12-01', 0.6800 UNION
> > SELECT '1965-03-01', 0.6800 UNION
> > SELECT '1965-06-01', 1.3500 UNION
> > SELECT '1965-09-01', 0.6700 UNION
> > SELECT '1965-12-01', 1.3200
> > I am trying to return the following results:
> > Qtr CPI YrCPI AvgYrCPI
> > --- -- -- ---
> > 1-Jun-60 1.48
> > 1-Sep-60 1.46
> > 1-Dec-60 0.72
> > 1-Mar-61 0.71 4.37
> > 1-Jun-61 0.71 3.60
> > 1-Sep-61 -0.70 1.44
> > 1-Dec-61 0.00 0.72 2.53
> > 1-Mar-62 0.00 0.01 1.44
> > 1-Jun-62 0.00 -0.70 0.37
> > 1-Sep-62 0.00 0.00 0.01
> > 1-Dec-62 0.00 0.00 -0.17
> > 1-Mar-63 0.00 0.00 -0.18
> > 1-Jun-63 0.00 0.00 0.00
> > 1-Sep-63 0.71 0.71 0.18
> > 1-Dec-63 0.00 0.71 0.36
> > 1-Mar-64 0.70 1.41 0.71
> > 1-Jun-64 0.70 2.11 1.24
> > 1-Sep-64 1.39 2.79 1.76
> > 1-Dec-64 0.68 3.47 2.45
> > 1-Mar-65 0.68 3.45 2.96
> > 1-Jun-65 1.35 4.10 3.45
> > 1-Sep-65 0.67 3.38 3.60
> > 1-Dec-65 1.32 4.02 3.74
> > Note, 4 data points are required to calculate a moving sum of CPI
> > (YrCPI) and 4 calculate YrCPI figures are required calculate the
> > annual average of YrCPI (AvgYrCPI), giving a staggered effect to the
> > first 7 results
> > This sad effort is about as far as I've got:
> > SELECT I.Qtr, I.CPI, SUM(S.CPI) AS YrCPI
> > FROM QtrInflation I
> > JOIN (
> > SELECT TOP 4 Qtr, CPI
> > FROM QtrInflation
> > ) S
> > ON S.Qtr <= I.Qtr
> > GROUP BY I.Qtr, I.CPI
> > ORDER BY I.Qtr ASC
> > Can anyone suggest how do achieve this result without having to resort
> > to cursors?
> > Thanks,
> > Stephen|||Hi Stephen

I would expect Steve's solution to work alot better than mine under
large loads!

John

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!|||>> I am trying to add a staggered running total and average to a query
returning quarterly CPI data. I need to add 4 quarterly data points
together to calculate a moving 12-month sum (YrCPI), and then to
complicate things, calculate a moving average of the 12-month figure
(AvgYrCPI). <<

I hope you mean to have a key on this table and some contraints

CREATE TABLE QtrInflation
(qtr SMALLDATETIME NOT NULL PRIMARY KEY
CHECK (MONTH(qtr) IN (03, 06, 09, 12)
AND (DAY(qtr) = 01)),
cpi DECIMAL(8,4) NOT NULL
CHECK(cpi >= 0.0000));

CREATE TABLE QtrReportRanges
(start_date SMALLDATETIME NOT NULL
CHECK (MONTH(qtr) IN (03, 06, 09, 12)
AND (DAY(qtr) = 01)),
end_date SMALLDATETIME NOT NULL
CHECK (MONTH(qtr) IN (03, 06, 09, 12)
AND (DAY(qtr) = 01)),
CHECK (start_date < end_date),
PRIMARY KEY (start_date < end_date));

INSERT INTO QtrReportRanges VALUES ('1960-03-01', '1960-12-01');
INSERT INTO QtrReportRanges VALUES ('1960-06-01', '1961-03-01');
etc,

now you can get the report easily.

SELECT R.start_date, R.end_date, SUM(cpi) AS yr_cpi, AVG(cpi) AS
avg_yr_cpi
FROM QtrInflation AS I, QtrReportRanges AS R
WHERE I.qtr BETWEEN R.start_date AND R.end_date
GROUP BY R.start_date, R.end_date;

adding some rows to a select

Hi folks,

I've a sql query problem I was wondering if you all had a quick and
dirty solution for. I've a query:

Select code, value from table_a where date in
(2004) and a_code in ('1000','2000') and b_code in ('01000','02000')

This returns a table that looks like:

A_CODE B_CODE VALUE
-- -- --

1000 01000 $500
1000 02000 $750

What I'd like to see is:

A_CODE B_CODE VALUE
-- -- --

1000 01000 $500
1000 02000 $750
2000 01000 $0
2000 02000 $0

Any suggestions on how to rewrite my query so the results show A_CODE
2000 with a VALUE of 0 or null?

Thank much in advance!

MarcMarc (brownjenkn@.aol.com) writes:
> I've a sql query problem I was wondering if you all had a quick and
> dirty solution for. I've a query:
> Select code, value from table_a where date in
> (2004) and a_code in ('1000','2000') and b_code in ('01000','02000')
> This returns a table that looks like:
> A_CODE B_CODE VALUE
> -- -- --
> 1000 01000 $500
> 1000 02000 $750
> What I'd like to see is:
> A_CODE B_CODE VALUE
> -- -- --
> 1000 01000 $500
> 1000 02000 $750
> 2000 01000 $0
> 2000 02000 $0
> Any suggestions on how to rewrite my query so the results show A_CODE
> 2000 with a VALUE of 0 or null?

CREATE TABLE a_code (a_code char(4) NOT NULL
CREATE TABLE b_code (b_code char(5) NOT NULL

go
INSERT a_code (a_code) VALUES ('1000')
INSERT a_code (a_code) VALUES ('2000')
INSERT b_code (b_code) VALUES ('01000')
INSERT b_code (b_code) VALUES ('02000')
go
SELECT a.a_code, b.b_code, coalesce(t.value, 0)
FROM (a_code a
CROSS JOIN b_code b)
LEFT JOIN table_a t ON a.a_code = t.a_code
AND b.b_code = t.b_code
ABD t.date = '2004'

Here I am handling a_code and b_code in the same way, so you will
get output for missing b_codes as well.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se

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

Adding Serial No in the Query Resultset

Hi to All!
Can any one help me in generating serial no in the query result?
e.g. i write a query it gives me 500 rows.
select name,fathername from abc
name FatherName
Harry David
Sarah Nenry
.
.
.
.
i want that reslut should come like that
S-no name FatherName
1 Harry David
2 Sarah Nenry
.
.
.
.
500 Farid Masood
how can i add this sequence no in query i have no S-no column?
Regards
Thanx
*** Sent via Developersdex http://www.examnotes.net ***1. Create a temp table with an Identity column
2. Insert your values into the temp table
3. Select * From the temp table and return that resultset.
Greg Jackson
PDX, Oregon|||http://www.aspfaq.com/2427
"Ghulam Farid" <gfaryd@.yahoo.com> wrote in message
news:uBPoaM2IGHA.2696@.TK2MSFTNGP14.phx.gbl...
> Hi to All!
> Can any one help me in generating serial no in the query result?
> e.g. i write a query it gives me 500 rows.
> select name,fathername from abc
> name FatherName
> Harry David
> Sarah Nenry
> .
> .
> .
> .
> i want that reslut should come like that
> S-no name FatherName
> 1 Harry David
> 2 Sarah Nenry
> .
> .
> .
> .
> 500 Farid Masood
> how can i add this sequence no in query i have no S-no column?
> Regards
> Thanx
>
> *** Sent via Developersdex http://www.examnotes.net ***|||Line numbering is an issue for the front end and has nothing to do with
the RDBMS. You can use a stinking dirty kludge with a proprietary
IDENTITY if you do not care about proper coding.
Have you ever had a software engineering course or read a book on
Software Engineering?|||"Aaron Bertrand [SQL Server MVP]" <ten.xoc@.dnartreb.noraa> wrote in message
news:%23YwLvk5IGHA.3176@.TK2MSFTNGP12.phx.gbl...

> http://www.aspfaq.com/2427
'Be sure to read KB #186133 for Microsoft's official word'
(How to dynamically number rows in a SELECT Transact-SQL statement)
Applies to 2005...?..well do the people that write this stuff read BOL?
Perhaps they want to keep some things a secret:)
www.rac4sql.net|||"--CELKO--" <jcelko212@.earthlink.net> wrote in message
news:1138413114.379715.161790@.g47g2000cwa.googlegroups.com...
> Line numbering is an issue for the front end and has nothing to do with
> the RDBMS. You can use a stinking dirty kludge with a proprietary
> IDENTITY if you do not care about proper coding.
> Have you ever had a software engineering course or read a book on
> Software Engineering?
Would you feel better substituting ranking for line numbering?
And I was having a hard time using 'stinking dirty kludge' in
a sentence.
Did you write for 'Laugh In'? :)|||>> Would you feel better substituting ranking for line numbering? <<
That is fine; ranking as a rule while putting a number on the output of
an un-ordred cursor is absurd and unrepeatable.
But do you have a bigger problem using it in a program :)? You
should.
Two gags only. And I do not remember what they were. They paid $50
for the two.|||I've posted something in the private groups so hopefully they will update to
reflect all the new bits that they brought in for SQL Server 2005.
Eg...
Tony Rogerson
SQL Server MVP
http://sqlserverfaq.com - free video tutorials
"05ponyGT" <nospam@.nospam> wrote in message
news:ejYR1SHJGHA.1188@.TK2MSFTNGP14.phx.gbl...
> "Aaron Bertrand [SQL Server MVP]" <ten.xoc@.dnartreb.noraa> wrote in
> message
> news:%23YwLvk5IGHA.3176@.TK2MSFTNGP12.phx.gbl...
>
> 'Be sure to read KB #186133 for Microsoft's official word'
> (How to dynamically number rows in a SELECT Transact-SQL statement)
> Applies to 2005...?..well do the people that write this stuff read BOL?
> Perhaps they want to keep some things a secret:)
> www.rac4sql.net
>|||select row_number() over ( order by name ), name
from sys.objects
order by name
Tony Rogerson
SQL Server MVP
http://sqlserverfaq.com - free video tutorials
"Tony Rogerson" <tonyrogerson@.sqlserverfaq.com> wrote in message
news:ui7ET6LJGHA.3408@.TK2MSFTNGP12.phx.gbl...
> I've posted something in the private groups so hopefully they will update
> to reflect all the new bits that they brought in for SQL Server 2005.
> Eg...
>
> --
> Tony Rogerson
> SQL Server MVP
> http://sqlserverfaq.com - free video tutorials
>
> "05ponyGT" <nospam@.nospam> wrote in message
> news:ejYR1SHJGHA.1188@.TK2MSFTNGP14.phx.gbl...
>

Sunday, March 11, 2012

adding root node in XML explicit query

I have sp called getLookupValue (using for xml explicit) that returns
multiple LookupType Node
<LookupType description="Claim Type">
<LookupValue lkvl_seq="10" lkvl_dsc="Accident" />
<LookupValue lkvl_seq="11" lkvl_dsc="Cancer" />
<LookupValue lkvl_seq="13" lkvl_dsc="Dental" />
</LookupType>
<LookupType description="File Source">
<LookupValue lkvl_seq="7" lkvl_dsc="AFLAC website" />
<LookupValue lkvl_seq="4" lkvl_dsc="Call" />
<LookupValue lkvl_seq="6" lkvl_dsc="Email" />
<LookupValue lkvl_seq="8" lkvl_dsc="Fax" />
<LookupValue lkvl_seq="5" lkvl_dsc="Letter" />
<LookupValue lkvl_seq="9" lkvl_dsc="Walk-in" />
</LookupType>
<LookupType description="File Type">
<LookupValue lkvl_seq="2" lkvl_dsc="CI" />
<LookupValue lkvl_seq="1" lkvl_dsc="EMF" />
<LookupValue lkvl_seq="3" lkvl_dsc="Media" />
</LookupType>
Can someone please let me know how can I modify the stored procedure to add
a root node.
Any sample code would help.
Thanks!
The easiest way to add a root node is to set the root node property on the
command object on the mid-tier.
SQL Server 2005 will have a ROOT() directive.
Best regards
Michael
"Manoj Agarwal" <ManojAgarwal@.discussions.microsoft.com> wrote in message
news:2DA49D31-E8B5-44DF-AF1A-30AC5DB72FC6@.microsoft.com...
>I have sp called getLookupValue (using for xml explicit) that returns
> multiple LookupType Node
>
> <LookupType description="Claim Type">
> <LookupValue lkvl_seq="10" lkvl_dsc="Accident" />
> <LookupValue lkvl_seq="11" lkvl_dsc="Cancer" />
> <LookupValue lkvl_seq="13" lkvl_dsc="Dental" />
> </LookupType>
> <LookupType description="File Source">
> <LookupValue lkvl_seq="7" lkvl_dsc="AFLAC website" />
> <LookupValue lkvl_seq="4" lkvl_dsc="Call" />
> <LookupValue lkvl_seq="6" lkvl_dsc="Email" />
> <LookupValue lkvl_seq="8" lkvl_dsc="Fax" />
> <LookupValue lkvl_seq="5" lkvl_dsc="Letter" />
> <LookupValue lkvl_seq="9" lkvl_dsc="Walk-in" />
> </LookupType>
> <LookupType description="File Type">
> <LookupValue lkvl_seq="2" lkvl_dsc="CI" />
> <LookupValue lkvl_seq="1" lkvl_dsc="EMF" />
> <LookupValue lkvl_seq="3" lkvl_dsc="Media" />
> </LookupType>
>
> Can someone please let me know how can I modify the stored procedure to
> add
> a root node.
> Any sample code would help.
> Thanks!
|||Hi Manoj,
look at this sample..hope this helps..dont worry about the length of the
code..look for what is needed.
output XML :
<products>
<product productID="" LastModifiedDate="">
<replacementPartList>
<replacementPart>
<partNumber></partNumber>
<name><![CDATA[]></name>
<erp></erp>
<revision></revision>
<version></version>
<environment> </environment>
<text><![CDATA[]]></text>
<conftext><![CDATA[]]></conftext>
</replacementPart>
<upgradeInfo><![CDATA[]]></upgradeInfo>
</replacementPartList>
<addOnPartList>
<addOnPart>
<name><![CDATA[]></name>
<erp></erp>
<revision></revision>
<version></version>
<environment> </environment>
<text><![CDATA[]]></text>
<conftext><![CDATA[]]></conftext>
</addOnPart>
<upgradeInfo><![CDATA[]]></upgradeInfo>
</addOnPartList>
</product>
</products>
Query :
SELECT
--product tag --
1 as tag
, NULL as parent
, NULL [products!1]
, NULL [product!2!productID]
, NULL [product!2!LastModifiedDate]
--replacementPart List --
--replacementPart List - add productID for Ordering. it needs to be
hidden. --
, NULL [replacementPartList!3!productID!hide]
--replacement Part--
, NULL [replacementPart!4!partNumber!element]
, NULL [replacementPart!4!name!element]
, NULL [replacementPart!4!erp!element]
, NULL [replacementPart!4!revision!element]
, NULL [replacementPart!4!version!element]
, NULL [replacementPart!4!environment!element]
, NULL [replacementPart!4!text!element]
, NULL [replacementPart!4!conftext!element]
--upgrade info--
, NULL [replacementPartList!3!upgradeInfo!element]
--AddOn Part List--
, NULL [addOnPartList!5!productID!hide]
--AddOn Part--
, NULL [addOnPart!6!partNumber!element]
, NULL [addOnPart!6!name!element]
, NULL [addOnPart!6!erp!element]
, NULL [addOnPart!6!revision!element]
, NULL [addOnPart!6!version!element]
, NULL [addOnPart!6!environment!element]
, NULL [addOnPart!6!text!element]
, NULL [addOnPart!6!conftext!element]
--upgrade info--
, NULL [addOnPartList!5!upgradeInfo!element]
UNION ALL
--Opening replacementPart List tag--
SELECT
--replacementPart List tag--
2 as tag
, 1 as parent
, NULL
, parts.ProductEditorialSKID
, ISNULL(Convert(Varchar(12),Max(parts.LastModifiedD ate),110),'')
--replacementPart List --
, NULL
--replacement Part--
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
--upgrade info--
, NULL
--AddOn Part List--
, NULL
--AddOn Part--
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
--upgrade info--
, NULL
FROM
#tblInfoWebParts parts
GROUP BY parts.ProductEditorialSKID
UNION ALL
--Opening replacementPart List tag--
SELECT
--replacementPart List tag--
3 as tag
, 2 as parent
, NULL
, parts.ProductEditorialSKID
, NULL
--replacementPart List --
, parts.ProductEditorialSKID
--replacement Part--
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
--upgrade info--
, (SELECT dbo.GetConcatenatedComments(parts.ProductEditorial SKID))
--AddOn Part List--
, NULL
--AddOn Part--
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
--upgrade info--
, NULL
FROM
#tblInfoWebParts parts
WHERE
parts.PartType <> 'A'
GROUP BY parts.ProductEditorialSKID
UNION ALL
--replacementPart--
SELECT
--replacementPart tag--
4 as tag
, 3 as parent
, NULL
, parts.ProductEditorialSKID
, NULL
--replacementPart List --
, parts.ProductEditorialSKID
--replacement Part--
, parts.PartNumber
, ISNULL(parts.ItemName,'')
, ISNULL(Convert(Varchar(10),parts.ERP),'')
, ISNULL(parts.RevisionName,'')
, ISNULL(parts.VersionName,'')
, ISNULL(parts.OperatingSystemName,'')
, ''
, ''
--upgrade info--
, NULL
--AddOn Part List--
, NULL
--AddOn Part--
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
--upgrade info--
, NULL
FROM
#tblInfoWebParts parts
WHERE
parts.PartType <> 'A' -- indicates that this part is a replacement part or
included part out of the bunch.
UNION ALL
--Add On Part List--
SELECT
--Add On Part List--
5 as tag
, 2 as parent
, NULL
, parts.ProductEditorialSKID
, NULL
--replacementPart List --
, NULL
--replacement Part--
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
--upgrade info--
, NULL
--AddOn Part List--
, parts.ProductEditorialSKID
--AddOn Part--
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
--upgrade info--
, (SELECT dbo.GetConcatenatedComments(parts.ProductEditorial SKID))
FROM
#tblInfoWebParts parts
WHERE
parts.PartType = 'A' -- indicates that this part is an add on part out of
the bunch.
GROUP BY parts.ProductEditorialSKID
UNION ALL
--Add On Part--
SELECT
--Add On Part--
6 as tag
, 5 as parent
, NULL
, parts.ProductEditorialSKID
, NULL
--replacementPart List --
, NULL
--replacement Part--
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
, NULL
--upgrade info--
, NULL
--AddOn Part List--
, parts.ProductEditorialSKID
--AddOn Part--
, ISNULL(parts.PartNumber,'')
, ISNULL(parts.ItemName,'')
, ISNULL(Convert(Varchar(10),parts.ERP),'')
, ISNULL(parts.RevisionName,'')
, ISNULL(parts.VersionName,'')
, ISNULL(parts.OperatingSystemName,'')
, ''
, ''
--upgrade info--
, NULL
FROM
#tblInfoWebParts parts
WHERE
parts.PartType = 'A' -- indicates that this part is an Add On Part out of
the bunch.
ORDER BY [products!1]
, [product!2!productID]
, [replacementPartList!3!productID!hide]
, [replacementPart!4!partNumber!element]
, [addOnPartList!5!productID!hide]
, [addOnPart!6!name!element]
FOR XML EXPLICIT
Av.
http://avdotnet.rediffblogs.com
http://www28.brinkster.com/avdotnet
"Manoj Agarwal" <ManojAgarwal@.discussions.microsoft.com> wrote in message
news:2DA49D31-E8B5-44DF-AF1A-30AC5DB72FC6@.microsoft.com...
> I have sp called getLookupValue (using for xml explicit) that returns
> multiple LookupType Node
>
> <LookupType description="Claim Type">
> <LookupValue lkvl_seq="10" lkvl_dsc="Accident" />
> <LookupValue lkvl_seq="11" lkvl_dsc="Cancer" />
> <LookupValue lkvl_seq="13" lkvl_dsc="Dental" />
> </LookupType>
> <LookupType description="File Source">
> <LookupValue lkvl_seq="7" lkvl_dsc="AFLAC website" />
> <LookupValue lkvl_seq="4" lkvl_dsc="Call" />
> <LookupValue lkvl_seq="6" lkvl_dsc="Email" />
> <LookupValue lkvl_seq="8" lkvl_dsc="Fax" />
> <LookupValue lkvl_seq="5" lkvl_dsc="Letter" />
> <LookupValue lkvl_seq="9" lkvl_dsc="Walk-in" />
> </LookupType>
> <LookupType description="File Type">
> <LookupValue lkvl_seq="2" lkvl_dsc="CI" />
> <LookupValue lkvl_seq="1" lkvl_dsc="EMF" />
> <LookupValue lkvl_seq="3" lkvl_dsc="Media" />
> </LookupType>
>
> Can someone please let me know how can I modify the stored procedure to
add
> a root node.
> Any sample code would help.
> Thanks!

adding query results to email body using CDOSYSmail

Thanks in advance - Steve.
I'm running SQL 7.0 with Exchange 2003 SP2 (SP.?) which uses SSL to preclude
using SQL Mail (as far as I know). So I've been working on using CDOSYSmail
to send email, and attachment, and the results from a stored procedure (a
set of queries that generates 6 summary reports with varying columns). I've
inserted the results from the stored procedure into a table called, results
varchar(4000).
I'm trying to insert the results from 'sproc_name' into the body of an email
and could use some help.
The stored procedure, 'usp_send_cdosysmail' is working fine except I can't
get the results from another stored procedure into the body of an email. The
table 'result' is one column varchar(4000); I'd prefer just executing the
'sproc_name' and avoid the cursor since i'm new to cursors. I receive the
error below:
Server: Msg 170, Level 15, State 1, Line 17
Line 17: incorrect syntax near @.body1
declare @.Body1 varchar(4000)
set @.Body1 = ''
declare r_cursor cursor for
select result from test.dbo.result
open r_cursor
declare @.r_return cursor
exec db_name.dbo.sproc_name @.r_return = OUTPUT
while (@.@.fetch_status=0)
begin
fetch next from @.r_return
end
close r_cursor
@.body1 = @.r_return
deallocate r_cursor
exec master..usp_send_cdosysmail
@.from='user1@.domain.com',
@.to ='user2@.domain.com',
@.subject ='Test',
@.body = @.body1,
@.attachments = 'C:\test.txt',
@.smtpserver = 'mailserver.domain.com',
@.bodytype ='TEXTBody' -- 'HTMLBody'Hi Steve
Assuming your result table is declared as something like:
CREATE TABLE dbo.result ( id int not null identity, result varchar(400))
Then each row returned from your stored procedure will be a separate row in
dbo.result. You can then cursor through the table and get each row.
INSERT INTO dbo.result (result)
EXEC dbo.sproc_name
DECLARE @.Body1 varchar(4000)
DECLARE @.lineresult varchar(400)
SET @.Body1 = ''
DECLARE r_cursor CURSOR FOR
SELECT result FROM dbo.result ORDER BY id
OPEN r_cursor
FETCH NEXT FROM r_cursor INTO @.Body1
WHILE @.@.FETCH_STATUS=0
BEGIN
FETCH NEXT FROM r_cursor INTO @.lineresult
SET @.Body1 = @.Body1 + CHAR(13) + CHAR(10) + @.lineresult
END
CLOSE r_cursor
DEALLOCATE r_cursor
John
"Steve" wrote:

> Thanks in advance - Steve.
> I'm running SQL 7.0 with Exchange 2003 SP2 (SP.?) which uses SSL to preclu
de
> using SQL Mail (as far as I know). So I've been working on using CDOSYSma
il
> to send email, and attachment, and the results from a stored procedure (a
> set of queries that generates 6 summary reports with varying columns). I'v
e
> inserted the results from the stored procedure into a table called, result
s
> varchar(4000).
> I'm trying to insert the results from 'sproc_name' into the body of an ema
il
> and could use some help.
> The stored procedure, 'usp_send_cdosysmail' is working fine except I can't
> get the results from another stored procedure into the body of an email. T
he
> table 'result' is one column varchar(4000); I'd prefer just executing the
> 'sproc_name' and avoid the cursor since i'm new to cursors. I receive the
> error below:
> Server: Msg 170, Level 15, State 1, Line 17
> Line 17: incorrect syntax near @.body1
> declare @.Body1 varchar(4000)
> set @.Body1 = ''
> declare r_cursor cursor for
> select result from test.dbo.result
> open r_cursor
> declare @.r_return cursor
> exec db_name.dbo.sproc_name @.r_return = OUTPUT
>
> while (@.@.fetch_status=0)
> begin
> fetch next from @.r_return
> end
> close r_cursor
> @.body1 = @.r_return
> deallocate r_cursor
> exec master..usp_send_cdosysmail
> @.from='user1@.domain.com',
> @.to ='user2@.domain.com',
> @.subject ='Test',
> @.body = @.body1,
> @.attachments = 'C:\test.txt',
> @.smtpserver = 'mailserver.domain.com',
> @.bodytype ='TEXTBody' -- 'HTMLBody'
>
>|||Hi John - big thanks!
I did not have an id property, only a column entitled results with datatype
varchar(4000).
Cursors need an id column (i'm familiar w/ the identity property - very
handy).
For my education, wow do the char(13) an char(10) work inconjunction with
@.body1 and @.lineresult to concatenate all the rows together? I interpret
@.body1 as being all the previous rows and @.lineresult being the current row,
but don't understand how char(13) and char(10) impact the query?
Thanks!
Steve
"John Bell" <jbellnewsposts@.hotmail.com> wrote in message
news:81EFD80A-10CE-4308-B710-7ABB7E79FD53@.microsoft.com...
> Hi Steve
> Assuming your result table is declared as something like:
> CREATE TABLE dbo.result ( id int not null identity, result varchar(400))
> Then each row returned from your stored procedure will be a separate row
in[vbcol=seagreen]
> dbo.result. You can then cursor through the table and get each row.
> INSERT INTO dbo.result (result)
> EXEC dbo.sproc_name
> DECLARE @.Body1 varchar(4000)
> DECLARE @.lineresult varchar(400)
> SET @.Body1 = ''
> DECLARE r_cursor CURSOR FOR
> SELECT result FROM dbo.result ORDER BY id
> OPEN r_cursor
> FETCH NEXT FROM r_cursor INTO @.Body1
> WHILE @.@.FETCH_STATUS=0
> BEGIN
> FETCH NEXT FROM r_cursor INTO @.lineresult
> SET @.Body1 = @.Body1 + CHAR(13) + CHAR(10) + @.lineresult
> END
> CLOSE r_cursor
> DEALLOCATE r_cursor
> John
> "Steve" wrote:
>
preclude[vbcol=seagreen]
CDOSYSmail[vbcol=seagreen]
(a[vbcol=seagreen]
I've[vbcol=seagreen]
results[vbcol=seagreen]
email[vbcol=seagreen]
can't[vbcol=seagreen]
The[vbcol=seagreen]
the[vbcol=seagreen]
the[vbcol=seagreen]|||Hi
The id column will be necessary if you want to keep the order the same as
the order returned by the stored procedure. The CHAR(13) and CHAR(10) are to
add a carriage return and linefeed into your results, they have no impact on
the query as they are not part of it. If you don't need them then they can b
e
omitted, but then the columns may not align.
@.Body1 was the variable you used for the email body, if you return more than
one line then the cursor will loop through subsequent lines by returning the
m
in @.lineresult and then appending them to @.Body1. The first line returned ca
n
go straight into @.Body1.
I am not sure how big the body of your text could be, but if it is 4000
characters it may not be large enough for your needs. You may want to look a
t
creating a DTS package to create the files and (say) using XPSMTP to send it
http://www.sqldev.net/xp/xpsmtp.htm. It may be better to put the results int
o
a spreadsheet rather than leaving them as text, DTS can do this. See books
online for more information on DTS and check out
http://www.sqldts.com/default.aspx
John
"Steve" wrote:

> Hi John - big thanks!
> I did not have an id property, only a column entitled results with datatyp
e
> varchar(4000).
> Cursors need an id column (i'm familiar w/ the identity property - very
> handy).
> For my education, wow do the char(13) an char(10) work inconjunction with
> @.body1 and @.lineresult to concatenate all the rows together? I interpret
> @.body1 as being all the previous rows and @.lineresult being the current ro
w,
> but don't understand how char(13) and char(10) impact the query?
> Thanks!
> Steve
> "John Bell" <jbellnewsposts@.hotmail.com> wrote in message
> news:81EFD80A-10CE-4308-B710-7ABB7E79FD53@.microsoft.com...
> in
> preclude
> CDOSYSmail
> (a
> I've
> results
> email
> can't
> The
> the
> the
>
>