473,804 Members | 3,789 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Loop through a recordset to populate columns in a temp table

I want to take the contents from a table of appointments and insert the
appointments for any given month into a temp table where all the
appointments for each day are inserted into a single row with a column
for each day of the month.
Is there a simple way to do this?

I have a recordset that looks like:

SELECT
a.Date,
a.Client --contents: Joe, Frank, Fred, Pete, Oscar
FROM
dbo.tblAppointm ents a
WHERE
a.date between ...(first and last day of the selected month)

What I want to do is to create a temp table that has 31 columns
to hold appointments and insert into each column any appointments for
the date...

CREATE TABLE #Appointments (id int identity, Day1 nvarchar(500), Day2
nvarchar(500), Day3 nvarchar(500), etc...)

Then loop through the recordset above to insert into Day1, Day 2, Day3,
etc. all the appointments for that day, with multiple appointments
separated by a comma.

INSERT INTO
#Appointments(D ay1)
SELECT
a.Client
FROM
dbo.tblAppointm ents a
WHERE
a.date = (...first day of the month)

(LOOP to Day31)
The results would look like
Day1 Day2 Day3 ...
Row1 Joe, Pete
Frank,
Fred

Maybe there's an even better way to handle this sort of situation?
Thanks,
lq

Jul 23 '05 #1
11 13613
You can use a query to do reports like this without looping or temp tables.
As specified it seems a little strange to list the dates horizontally since
there is apparently no data on the vertical axis but the rest is really just
a matter of formatting once you have the basic query. Formatting is best
done client-side rather than in the database.

DECLARE @dt DATETIME
/* First date of the month */
SET @dt = '20050501'

SELECT
MAX(CASE WHEN DATEDIFF(DAY,@d t,date)=0 THEN client END),
MAX(CASE WHEN DATEDIFF(DAY,@d t,date)=1 THEN client END),
MAX(CASE WHEN DATEDIFF(DAY,@d t,date)=2 THEN client END),
...
MAX(CASE WHEN DATEDIFF(DAY,@d t,date)=30 THEN client END)
FROM tblAppointments
WHERE date >= @dt
AND date < DATEADD(MONTH,1 ,@dt)
GROUP BY client

--
David Portas
SQL Server MVP
--
Jul 23 '05 #2
laurenq uantrell wrote:
I want to take the contents from a table of appointments and insert the
appointments for any given month into a temp table where all the
appointments for each day are inserted into a single row with a column
for each day of the month.
Is there a simple way to do this?

I have a recordset that looks like:

SELECT
a.Date,
a.Client --contents: Joe, Frank, Fred, Pete, Oscar
FROM
dbo.tblAppointm ents a
WHERE
a.date between ...(first and last day of the selected month)

What I want to do is to create a temp table that has 31 columns
to hold appointments and insert into each column any appointments for
the date...

CREATE TABLE #Appointments (id int identity, Day1 nvarchar(500), Day2
nvarchar(500), Day3 nvarchar(500), etc...)

Then loop through the recordset above to insert into Day1, Day 2, Day3,
etc. all the appointments for that day, with multiple appointments
separated by a comma.

INSERT INTO
#Appointments(D ay1)
SELECT
a.Client
FROM
dbo.tblAppointm ents a
WHERE
a.date = (...first day of the month)

(LOOP to Day31)
The results would look like
Day1 Day2 Day3 ...
Row1 Joe, Pete
Frank,
Fred

Maybe there's an even better way to handle this sort of situation?
Thanks,
lq


You're talking about crosstab queries. Here's a page of links that may
be of use:

http://www.google.com/custom?q=cross...D%3A1%3B&hl=en

--
MGFoster:::mgf0 0 <at> earthlink <decimal-point> net
Oakland, CA (USA)
Jul 23 '05 #3
laurenq uantrell (la************ *@hotmail.com) writes:
I want to take the contents from a table of appointments and insert the
appointments for any given month into a temp table where all the
appointments for each day are inserted into a single row with a column
for each day of the month.
Is there a simple way to do this?
...
Then loop through the recordset above to insert into Day1, Day 2, Day3,
etc. all the appointments for that day, with multiple appointments
separated by a comma.


I'm a afraid that loop is what you will have to do. And write 31
UPDATE statements, one for each day of the month. There are ways to
build comma-separated lists with set-based statements, but the
methods used are unsupported and undefined, and cannot be trusted.
So the only way to build a CSV is to run a cursor.

OK, you don't really need 31 UPDATE statements. You could aggregate
data into a table with one per date, and then at then end run a
31-way self cross-join to produce the final result.

Certainly, a client program is much better apt to do this sort
of thing.

--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 23 '05 #4
David, thanks for that. I thought it must be pretty straignt forward.
The reason I want it all in one row and the days data in columns is
that I want to populate a sincle record on a form that resembles a
monthly calendar but cwhich in fact is simply 31 text boxes. Previously
I had a form that populated 31 different subforms by looping through
the dates on the client side and it is too slow.THanks,
lq

Jul 23 '05 #5
David, thanks for that. I thought it must be pretty straight forward.
The reason I want it all in one row and the days data in columns is
that I want to populate a sincle record on a form that resembles a
monthly calendar but cwhich in fact is simply 31 text boxes. Previously
I had a form that populated 31 different subforms by looping through
the dates on the client side and it is too slow.THanks,
lq

Jul 23 '05 #6
Erland,
My solution is to run a UDFwithin a View that creates the comma
separated list for each date of appointments. That part works fine on a
single date, and now I'm just figuring out how to loop through the
dates: first day of the month + 31 days.
Thanks.
lq

Jul 23 '05 #7
Erland,
You got me in the right direction and the solution works very fast:

The stored procedure:

@ClienID int,
@dt datetime /* first day of the selected month */

AS

DECLARE @dtEnd datetime
SET @dtEnd = DATEADD(DAY,-1,DATEADD(MONTH ,1,@dt)) /* last day of the
selected month */

SELECT
dbo.fn_ClientSk ed(@dt, @ClientID) AS D1,
dbo.fn_ClientSk ed(DATEADD(DAY, 1,@dt), @ClientID) AS D2,
dbo.fn_ClientSk ed(DATEADD(DAY, 2,@dt), @ClientID) AS D3,
etc...(for D4-D28)
CASE WHEN DATEADD(DAY,28, @dt) <= @dtEnd THEN
dbo.fn_ClientSk ed(DATEADD(DAY, 28,@dt), @ClientID) END AS D29,
CASE WHEN DATEADD(DAY,29, @dt) <= @dtEnd THEN
dbo.fn_ClientSk ed(DATEADD(DAY, 29,@dt), @ClientID) END AS D30,
CASE WHEN DATEADD(DAY,30, @dt) <= @dtEnd THEN
dbo.fn_ClientSk ed(DATEADD(DAY, 30,@dt), @ClientID) END AS D31
The UDF:

CREATE function dbo.fn_ClientSk ed(@dtX as DateTime, @ClientID as int)
returns
nvarchar(500)
AS
begin
declare @ret_value nvarchar(500)
SET @ret_value=''
Select @ret_value=@ret _value + '; ' + AppointmentTitl e
FROM dbo.tblAppointm ents
WHERE
tblAppointments .ClientID = @ClientID
AND
@dtX Between tblAppointments .StartDate AND tblAppointments .EndDate
RETURN CASE WHEN LEN(@ret_value) >0 THEN
RIGHT(@ret_valu e,LEN(@ret_valu e)-2) ELSE '' END
end

Note: This particular UDF returns all appointments by day of the month
for the same client to populate a monthly calendar. It can be easily
modified to show appointments by employee, etc.

Jul 23 '05 #8
laurenq uantrell (la************ *@hotmail.com) writes:
You got me in the right direction and the solution works very fast:
...
declare @ret_value nvarchar(500)
SET @ret_value=''
Select @ret_value=@ret _value + '; ' + AppointmentTitl e
FROM dbo.tblAppointm ents
WHERE
tblAppointments .ClientID = @ClientID
AND
@dtX Between tblAppointments .StartDate AND tblAppointments .EndDate
RETURN CASE WHEN LEN(@ret_value) >0 THEN
RIGHT(@ret_valu e,LEN(@ret_valu e)-2) ELSE '' END
end


While it may work and be fast, it relies on undefined behaviour. See
http://support.microsoft.com/default.aspx?scid=287515.
--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 23 '05 #9
Erland,
Now you have me worried. Because I am using a UDF within the SELECT
statement? Isn't that what they're for?
I chose this solution because the other solutions I conceived required
31 server calls to populate 31 subforms (one for each day of the week.)
With the method above the data is all shoved down the pipe as one row.
Isn't that a preferable solution where a simple string output is all
that's required for each date?
lq

Jul 23 '05 #10

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

Similar topics

2
4084
by: Nick | last post by:
Loop to create an array from a dynamic form. I'm having trouble with an application, and I'll try to explain it as clearly as possible: 1. I have a form with two fields, say Apples and Oranges. The user selects from a drop down menu, between 1-10 of each and clicks submit. The resulting page will display a NEW form, with rows and a list of fields for the amount of each items selected.
0
2881
by: elcc1958 | last post by:
I need to support a VB6 application that will be receiving disconnected ADODB.Recordset from out DotNet solution. Our dotnet solution deals with System.Data.DataTable. I need to populate a disconnected ADODB.Recordset from System.Data.DataTable data. Below is the source code I am implementing to test the process. I do not get any error, that I can see. The problem I have is that at the end, the recordset seems to be empty. Any...
20
2772
by: Steve Jorgensen | last post by:
Hi all, I've just finished almost all of what has turned out to be a real bear of a project. It has to import data from a monthly spreadsheet export from another program, and convert that into normalized data. The task is made more difficult by the fact that the structure itself can vary from month to month (in well defined ways). So, I used the SQL-centric approach, taking vertical stripes at a time so that, for instance, for each...
22
2897
by: Gerry Abbott | last post by:
Hi all, I having some confusing effects with recordsets in a recent project. I created several recordsets, each set with the same number of records, and related with an index value. I create a table and add the index value and a value/s from each recordset in turn, into a temporary table, which I used to create a report. I created this with DAO objects, and it worked fine. I use iteration, and the ..movenext command to get the next...
4
2735
by: Kathy | last post by:
Hi All, I am using Access 2000. I would like to streamline this code by using a variable for the column name. I have three tables with 255 columns each that I would like to populate with the data from one table that has 1 column. Each of the three tables will each up with 1 record with 255 columns. This is the code I wrote (in brief) to demonstare whate I want to do. Is there an easier way? I don't really want to type 500 lines of code...
52
6360
by: MP | last post by:
Hi trying to begin to learn database using vb6, ado/adox, mdb format, sql (not using access...just mdb format via ado) i need to group the values of multiple fields - get their possible variations(combination of fields), - then act on each group in some way ...eg ProcessRs (oRs as RecordSet)... the following query will get me the distinct groups
2
9436
by: rn5a | last post by:
In a ASP applicatiuon, the FOrm has a textbox & a select list where the admin can select multiple options. Basically the admin has to enter the name of a new coach in the textbox & select the soccer clubs which he will be coaching; thus he can select only one soccer club for a new coach or multiple soccer clubs. This is how I am trying it: When this Form will be submitted, the new coaches name will be inserted in a MS-Access DB table...
22
2058
by: kjworm | last post by:
Greetings everyone, I am working on a scheduling tool and have a temp table that I am attempting to loop through to pull the necessary info out of before deleting. I am using Access '97 on Windows XP. Here is my code: Private Sub ScheduleParts_Click()
4
2587
by: ipez75 | last post by:
Hello everyone, I have a web application written in asp 6.0, my problem is that I execute a sql server store procedure and I get an empty recordset, while executing the same sp on query anlyzer I can see 5 records. Basically the sp create a temp table, populate it, and lastly selects the results from the temp table. I read on a preceding post to insert the clause: "SET NOCOUNT ON" to avoid getting closed recordset of the insert statements, so...
0
9706
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9579
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10332
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10320
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9150
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7620
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5521
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3820
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2991
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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

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