Showing posts with label columns. Show all posts
Showing posts with label columns. Show all posts

Sunday, March 11, 2012

Calling a function inside of a function is not allowed in sql server?

We have a stored procedure that generates a unique random integer which uses
the RAND function. For data columns, you can invoke a function to create a
default value .e.x.: NEWID(). I would like to call a function that will
perform the same operations as the stored procedure.
The sql guru here says he tried to make our stored prodecure a function but
wasn't able to because sql server2k wouldn't allow him to use RAND inside
the function. Does anyone know of any workarounds, will future verions of
sql server allow this?
Thx in advance.Pass RAND() into the function (this is much the same as GETDATE()). Look up
DETERMINISTIC and NONDETERMINISTIC. See http://www.aspfaq.com/2439
--
http://www.aspfaq.com/
(Reverse address to reply.)
"Hasani (remove nospam from address)" <hblackwell@.n0sp4m.popstick.com> wrote
in message news:uK2Qeh1lEHA.3496@.TK2MSFTNGP12.phx.gbl...
> We have a stored procedure that generates a unique random integer which
uses
> the RAND function. For data columns, you can invoke a function to create a
> default value .e.x.: NEWID(). I would like to call a function that will
> perform the same operations as the stored procedure.
> The sql guru here says he tried to make our stored prodecure a function
but
> wasn't able to because sql server2k wouldn't allow him to use RAND inside
> the function. Does anyone know of any workarounds, will future verions of
> sql server allow this?
> Thx in advance.
>|||Works great, THX!!!!!!!
"Aaron [SQL Server MVP]" <ten.xoc@.dnartreb.noraa> wrote in message
news:uWRx%23m1lEHA.3432@.TK2MSFTNGP14.phx.gbl...
> Pass RAND() into the function (this is much the same as GETDATE()). Look
> up
> DETERMINISTIC and NONDETERMINISTIC. See http://www.aspfaq.com/2439
> --
> http://www.aspfaq.com/
> (Reverse address to reply.)
>
>
> "Hasani (remove nospam from address)" <hblackwell@.n0sp4m.popstick.com>
> wrote
> in message news:uK2Qeh1lEHA.3496@.TK2MSFTNGP12.phx.gbl...
>> We have a stored procedure that generates a unique random integer which
> uses
>> the RAND function. For data columns, you can invoke a function to create
>> a
>> default value .e.x.: NEWID(). I would like to call a function that will
>> perform the same operations as the stored procedure.
>> The sql guru here says he tried to make our stored prodecure a function
> but
>> wasn't able to because sql server2k wouldn't allow him to use RAND inside
>> the function. Does anyone know of any workarounds, will future verions of
>> sql server allow this?
>> Thx in advance.
>>
>

Calling a function inside of a function is not allowed in sql server?

We have a stored procedure that generates a unique random integer which uses
the RAND function. For data columns, you can invoke a function to create a
default value .e.x.: NEWID(). I would like to call a function that will
perform the same operations as the stored procedure.
The sql guru here says he tried to make our stored prodecure a function but
wasn't able to because sql server2k wouldn't allow him to use RAND inside
the function. Does anyone know of any workarounds, will future verions of
sql server allow this?
Thx in advance.
Pass RAND() into the function (this is much the same as GETDATE()). Look up
DETERMINISTIC and NONDETERMINISTIC. See http://www.aspfaq.com/2439
http://www.aspfaq.com/
(Reverse address to reply.)
"Hasani (remove nospam from address)" <hblackwell@.n0sp4m.popstick.com> wrote
in message news:uK2Qeh1lEHA.3496@.TK2MSFTNGP12.phx.gbl...
> We have a stored procedure that generates a unique random integer which
uses
> the RAND function. For data columns, you can invoke a function to create a
> default value .e.x.: NEWID(). I would like to call a function that will
> perform the same operations as the stored procedure.
> The sql guru here says he tried to make our stored prodecure a function
but
> wasn't able to because sql server2k wouldn't allow him to use RAND inside
> the function. Does anyone know of any workarounds, will future verions of
> sql server allow this?
> Thx in advance.
>
|||Works great, THX!!!!!!!
"Aaron [SQL Server MVP]" <ten.xoc@.dnartreb.noraa> wrote in message
news:uWRx%23m1lEHA.3432@.TK2MSFTNGP14.phx.gbl...
> Pass RAND() into the function (this is much the same as GETDATE()). Look
> up
> DETERMINISTIC and NONDETERMINISTIC. See http://www.aspfaq.com/2439
> --
> http://www.aspfaq.com/
> (Reverse address to reply.)
>
>
> "Hasani (remove nospam from address)" <hblackwell@.n0sp4m.popstick.com>
> wrote
> in message news:uK2Qeh1lEHA.3496@.TK2MSFTNGP12.phx.gbl...
> uses
> but
>

Wednesday, March 7, 2012

Call function from a procedure and assign return value to variable (sql server)

Hi all,
I have a procedure proc1, which needs to update a table.
One of the columns to update the table is calculated using a function
funct1 (which returns a smalldatetime)
My problem is how do I call the function funct1 from procedure proc1,
so that the return value of function is saved in a variable in
procedure.
Sample Procedure Proc1
ALTER PROCEDURE proc1
@.x int
AS
declare @.ret smalldatetime
--Here, I want @.ret to be a smalldatetime value returned by function
funct1.
--I tried the below (though knowing it wont work):
--@.ret = select dbo.funct1(param1), but it gives error.
--I even tried(again, though knowing it wont work):
--update myTable set field1 = select dbo.funct1(param1), but it gives
error.
--WHERE ...
update myTable set field1 = @.ret
WHERE ...
Sample function funct1:
alter FUNCTION dbo.funct1
(
@.val1 decimal,
@.val2 int
)
RETURNS smalldatetime
AS
BEGIN
DECLARE @.ret1 decimal
DECLARE @.ret2 smalldatetime
DECLARE sel_Cursor CURSOR FOR SELECT field1, field2
FROM myTable
OPEN sel_Cursor
FETCH NEXT FROM sel_Cursor INTO @.ret1, @.ret2
CLOSE sel_Cursor
DEALLOCATE sel_Cursor
if @.val1 = @.ret2
return @.ret2
else
set @.ret2 = some function...
RETURN @.ret2
END
---
Pls help..
TIA..Whats the error ? Normally you could use it by using this sample query
SELECT @.ret = dbo.SomeFunction(@.SomeParam)
HTH, Jens Suessmeyer.|||Thanks guys..
Damn, I dont knw why i was using the 'select'. Now it worked for me.
Trey,
I am using the cursor to fetch value and assign it to a variable.
The 'where' clause fetches single row.
And the select query returns single value.
But still i have used cursor coz thts the only way I know (I am pretty
new to SQL :( ).
Is there any other way to do so'
Trey Walpole wrote:
> What is that cursor supposed to be doing?
> Are you really looping through the whole table to get a single value'
> And possibly some random value at that?
> i cannot in good conscience give you an answer and let you keep that UDF..
.
>
> Chris wrote:|||Chris wrote:
> Hi all,
> I have a procedure proc1, which needs to update a table.
> One of the columns to update the table is calculated using a function
> funct1 (which returns a smalldatetime)
> My problem is how do I call the function funct1 from procedure proc1,
> so that the return value of function is saved in a variable in
> procedure.
>
> Sample Procedure Proc1
> ALTER PROCEDURE proc1
> @.x int
> AS
> declare @.ret smalldatetime
> --Here, I want @.ret to be a smalldatetime value returned by function
> funct1.
> --I tried the below (though knowing it wont work):
> --@.ret = select dbo.funct1(param1), but it gives error.
> --I even tried(again, though knowing it wont work):
> --update myTable set field1 = select dbo.funct1(param1), but it gives
> error.
> --WHERE ...
> update myTable set field1 = @.ret
> WHERE ...
>
> Sample function funct1:
> alter FUNCTION dbo.funct1
> (
> @.val1 decimal,
> @.val2 int
> )
> RETURNS smalldatetime
> AS
> BEGIN
> DECLARE @.ret1 decimal
> DECLARE @.ret2 smalldatetime
> DECLARE sel_Cursor CURSOR FOR SELECT field1, field2
> FROM myTable
> OPEN sel_Cursor
> FETCH NEXT FROM sel_Cursor INTO @.ret1, @.ret2
> CLOSE sel_Cursor
> DEALLOCATE sel_Cursor
> if @.val1 = @.ret2
> return @.ret2
> else
> set @.ret2 = some function...
> RETURN @.ret2
> END
> ---
> Pls help..
> TIA..
Why does the function use a cursor? Why don't you just assign the
result of the function to a variable?
Please post DDL, sample data and required results as described in:
http://www.aspfaq.com/etiquette.asp?id=5006
David Portas
SQL Server MVP
--|||Chris wrote:
> Thanks guys..
> Damn, I dont knw why i was using the 'select'. Now it worked for me.
> Trey,
> I am using the cursor to fetch value and assign it to a variable.
> The 'where' clause fetches single row.
> And the select query returns single value.
> But still i have used cursor coz thts the only way I know (I am pretty
> new to SQL :( ).
> Is there any other way to do so'
>
In that case you probably don't need the cursor or the function. You
can do it in the UPDATE. For example:
UPDATE your_table
SET col =
(SELECT col
FROM other_table
WHERE ...)
WHERE ...
etc.
Set-based code should be your first choice for this kind of thing. If
you are new to SQL then you shouldn't be using cursors AT ALL. You can
do a lot of damage that way.
David Portas
SQL Server MVP
--|||Hey david,
In the function, I am doing calculation with two different tables, and
the value returned is compared with the parameter i am passing in the
function.
If the values are same, I am not supposed to change the value in
tables.
If its different, some calculations are made, and the new value is
inserted.
For this, I am using cursor, because I need to save value to a variable
to compare, as well as calculate.|||Chris wrote:
> Hey david,
> In the function, I am doing calculation with two different tables, and
> the value returned is compared with the parameter i am passing in the
> function.
> If the values are same, I am not supposed to change the value in
> tables.
> If its different, some calculations are made, and the new value is
> inserted.
> For this, I am using cursor, because I need to save value to a variable
> to compare, as well as calculate.
A) You don't need to use a cursor to assign a value to a variable. You
can use SET
SET @.var =
(SELECT col
FROM your_table
WHERE ...)
For multiple assignment you can use SELECT:
SELECT @.col1 = col1, @.col2 = col2
FROM your_table
WHERE ...
B) You don't need a function to do all the joins and calculations you
talked about. You should be able to do that in an UPDATE statement in
almost every case. Most cases, doing it in the UPDATE statement will
perform better than using a function.
Unfortunately you didn't give us enough information to reply with
alternative solutions. That's why the convention is to post DDL, sample
data, and your required end results. I posted a link earlier that
explained how to do that.
Let me explain why I said you shouldn't use cursors. I didn't meant
that as serious advice rather than a rebuke. The reason is that most of
the time cursors are a bad choice for solving problems in SQL. Those
who don't know SQL well tend to write over-complex, inefficient and
buggy cursor code. Only when you know SQL really well will you have the
experience to know when a cursor is a sensible idea. Until then it
really is safest to avoid them altogether.
Hope this helps.
David Portas
SQL Server MVP
--|||Thanx for the help Dave,
I will try doing it this way..

Saturday, February 25, 2012

Calendar Style Report

Any ideas on how I might be able to create a report with a page for each
month, columns for each day, rows for each week and scheduled activities on
the appropriate date?
I have a db with rows for each activity and columns for various types of
dates, i.e, start, review, submit, etc.
TIA
deanIt's actually quite a lot of work...
You need to drive the report from a dataset that has generated calendar data
in it, and join your real data to this table on the date values. Then of
course you can group on month and week in the standard way.
There are two tricky parts. The first is generating the calendar data --
have you ever done this before? Here is an example -- not sure if this is
exactly the same as the one that I use, but it looks similar.
http://blogs.x2line.com/al/archive/2004/04/10/229.aspx
The second is a *bit* tricky, but mostly it is tedious: setting up the
columns for all the days in any given week. The information for each column
has a different offset (starting with 0 and going to 6) from the first day
of week.
Basically, it's a lot of SQL.
>L<
"Dean" <Dean@.discussions.microsoft.com> wrote in message
news:938ADD6C-2509-40C5-8339-AED5B2EC9224@.microsoft.com...
> Any ideas on how I might be able to create a report with a page for each
> month, columns for each day, rows for each week and scheduled activities
> on
> the appropriate date?
> I have a db with rows for each activity and columns for various types of
> dates, i.e, start, review, submit, etc.
> TIA
> dean

Thursday, February 16, 2012

Calculating Time Difference

Hi,

I have a table called Bookings which has two important columns;
Booking_Start_Time and Booking_End_Time. These columns are both of type
DATETIME. Given any day how can I calculate how many hours are available
between the hours of 09.00 and 17.30 so a user can see at a glance how many
hours they have unbooked on a particular day (i.e. 8.5 hours less the time
of any bookings on that day), can this be done with a query
or do I have to work it out in my code?

Thanks for your helpShaun,

Take a look at DateDiff function in books online. Something like this will
help you. This query return the available time in minutes.

select Date,
DateDiff(minute, '09:00','17:30') - Sum(BookTime)
from (select convert(char(10), Booking_Start_Time, 112) as Date,
DateDiff(minute, Booking_Start_Time, Booking_End_Time) as
BookTime
from YourTable
) as Tmp
group by Date

Shervin

"Shaun" <shaun@.mania.plus.com> wrote in message
news:blc5m3$fug$1@.reader-00.news.insnet.cw.net...
> Hi,
> I have a table called Bookings which has two important columns;
> Booking_Start_Time and Booking_End_Time. These columns are both of type
> DATETIME. Given any day how can I calculate how many hours are available
> between the hours of 09.00 and 17.30 so a user can see at a glance how
many
> hours they have unbooked on a particular day (i.e. 8.5 hours less the time
> of any bookings on that day), can this be done with a query
> or do I have to work it out in my code?
> Thanks for your help|||"Shaun" <shaun@.mania.plus.com> wrote in message news:blc5m3$fug$1@.reader-00.news.insnet.cw.net...
> Hi,
> I have a table called Bookings which has two important columns;
> Booking_Start_Time and Booking_End_Time. These columns are both of type
> DATETIME. Given any day how can I calculate how many hours are available
> between the hours of 09.00 and 17.30 so a user can see at a glance how many
> hours they have unbooked on a particular day (i.e. 8.5 hours less the time
> of any bookings on that day), can this be done with a query
> or do I have to work it out in my code?
> Thanks for your help

Here's a solution that allows bookings to overlap, multiple interested
non-overlapping intervals to be specified (you had specified one, 0900
to 1730) and both bookings and interested intervals to span more than
one day.

-- Bookings can overlap
CREATE TABLE Bookings
(
booking_start_time DATETIME NOT NULL,
booking_end_time DATETIME NOT NULL,
CHECK (booking_end_time >= booking_start_time),
PRIMARY KEY (booking_start_time, booking_end_time)
)

-- Sample data
INSERT INTO Bookings (booking_start_time, booking_end_time)
VALUES ('20030930 8:30AM', '20030930 10:30AM')
INSERT INTO Bookings (booking_start_time, booking_end_time)
VALUES ('20030930 10:00 AM', '20030930 12:30PM')
INSERT INTO Bookings (booking_start_time, booking_end_time)
VALUES ('20030930 2:00PM', '20030930 4:30PM')
INSERT INTO Bookings (booking_start_time, booking_end_time)
VALUES ('20030930 9:00PM', '20030930 11:30PM')

-- Interested intervals can't overlap
CREATE TABLE InterestedIntervals
(
interval_start DATETIME NOT NULL,
interval_end DATETIME NOT NULL,
CHECK (interval_end >= interval_start),
PRIMARY KEY (interval_start, interval_end)
)

-- Sample data
-- Note that multiple interested intervals can be specified
INSERT INTO InterestedIntervals (interval_start, interval_end)
VALUES ('20030930 8:00AM', '20030930 1:00PM')
INSERT INTO InterestedIntervals (interval_start, interval_end)
VALUES ('20030930 2:00PM', '20030930 6:00PM')
INSERT INTO InterestedIntervals (interval_start, interval_end)
VALUES ('20030930 8:00PM', '20030930 11:59PM')

CREATE VIEW OrderedBookings (interval_start, interval_end, seq)
AS
SELECT B1.booking_start_time,
B1.booking_end_time,
(SELECT COUNT(*)
FROM Bookings AS B2
WHERE B2.booking_start_time < B1.booking_start_time OR
(B2.booking_start_time = B1.booking_start_time AND
B2.booking_end_time < B1.booking_end_time))
FROM Bookings AS B1

-- A DATETIME value can be from date 17530101 to date 99991231
CREATE VIEW BookingGaps (interval_start, interval_end)
AS
SELECT '17530101' AS interval_start, interval_start AS interval_end
FROM OrderedBookings
WHERE seq = 0 AND interval_start > '17530101'
UNION ALL
SELECT OI1.interval_end AS interval_start,
COALESCE(OI2.interval_start, '99991231') AS interval_end
FROM OrderedBookings AS OI1
LEFT OUTER JOIN
OrderedBookings AS OI2
ON OI2.seq = OI1.seq + 1
WHERE OI2.interval_start > OI1.interval_end OR
OI2.seq IS NULL

CREATE VIEW InterestedBookingGaps (interval_start, interval_end)
AS
SELECT CASE WHEN G.interval_start BETWEEN
I.interval_start AND I.interval_end
THEN G.interval_start
ELSE I.interval_start
END,
CASE WHEN G.interval_end BETWEEN
I.interval_start AND I.interval_end
THEN G.interval_end
ELSE I.interval_end
END
FROM BookingGaps AS G
INNER JOIN
InterestedIntervals AS I
ON NOT(I.interval_start >= G.interval_end OR
I.interval_end <= G.interval_start)

-- Booking gaps with respect to interested intervals
SELECT interval_start, interval_end
FROM InterestedBookingGaps
ORDER BY interval_start

interval_start interval_end
2003-09-30 08:00:00.000 2003-09-30 08:30:00.000
2003-09-30 12:30:00.000 2003-09-30 13:00:00.000
2003-09-30 16:30:00.000 2003-09-30 18:00:00.000
2003-09-30 20:00:00.000 2003-09-30 21:00:00.000
2003-09-30 23:30:00.000 2003-09-30 23:59:00.000

-- Free time
SELECT COALESCE(SUM(DATEDIFF(MINUTE, interval_start, interval_end))
/ 60.0, 0) AS hours_free,
COALESCE(SUM(DATEDIFF(MINUTE, interval_start, interval_end)), 0)
AS minutes_free
FROM InterestedBookingGaps

hours_free minutes_free
3.983333 239

Regards,
jag

calculating the sum of columns...

It may be simple question, but how can i get the sum of column? with conditions like getting the some of clicks one user send and so...You can use the SUM function.|||

I know, but i have syntax errors, i use:

"SELECT * SUM(payed) from tbl_links where site='1'",

and get errors, i just couldn't find the right way...

|||Please post your table structure, some sample data and your SQL query and the error message. The more info you provide the better are the chances of receiving help and faster is the response time.|||

thaks for your reply's

the table structure:

columns:

ID, siteid (for the sending site), adid (the ad the user clicked), sum (the price we should pay to the site)

all columns are int's

the code line:

cmd.CommandText = "SELECT * SUM([sum]) FROM tbl_clicks WHERE siteid='" & sitename.SelectedItem.Value & "'"

and the error massege:

Incorrect syntax near 'SUM'

thanks for the help.

|||

(1) Your T-SQL is syntactically incorrect. you have to separate columns with a comma.

(2) You cannot use aggregate function with a "*". You need to list out the column names and use GROUP BY. Check out BOL for more info. If you simply want the sum you can do

SELECT SUM([sum]) FROM tbl_clicks WHERE siteid='" & sitename.SelectedItem.Value & "'"

(3) Use parameterized queries, without which your application is prone to SQL Injection attacks.

Tuesday, February 14, 2012

Calculating Overdue Days

I have table with three columns: 1) TodaysDate,
2)DueBackDate,
3) DaysOverdue
The problem I am having is creating a formula in MS SQL, so that whenthe 'DueBackDate' column is more than todays date, I want the'DaysOverdue' column to be incremented accordingly.
I have tried creating an SQL Query something like this:
UPDATE rental
SET DaysOverdue = DaysOverdue + 1
WHERE ({ fn NOW() } > DueBackDate)
But the problem with this that it only increments the 'DaysOverdue'field by 1. When I want it to basically subtract todays date by'DueBackDate'.
I have tried to also create a formula within MS SQL but I come up witherrors. I have done something like this in Access which worked. TheFormula looked like this:
IIF(Now()>[DueBackDate],int(Now()-[DueBackDate]),0)
Is there a way to convert this formula so that is would work in MS SQL?
Thanks.
I now found a solution by using the DatePart Function.
Stick out tongue [:P]
|||DatePart or DateDiff?
|||When I used DatePart, my SQL Query was like this:
UPDATE table
SET DaysOverdue = DATEPART(dd, { fn NOW() }) - DATEPART(dd, DueBackDate)
WHERE ({ fn NOW() } > DueBackDate)

|||The funny thingabout programming is that there are usually several ways to solve thesame problem. You might consider using the DATEDIFF functioninstead. It was made for exactly this purpose. And use thebuilt-in GETDATE() function instead of{ fn NOW() }.
I was thinking of something like this, which should perform better for you:
DECLARE @.today datetime
SELECT @.today = GETDATE()
UPDATE
table
SET
DaysOverdue = DATEDIFF(dd,DueBackDate,@.today)
WHERE
@.today > DueBackDate

I opted to storethe current date/time in a @.today variable, so that I could be certainthat the same exact date/time would be used for the entirestatement. This would be important should the execution periodcross a date boundary, plus there's no reason for SQL to have todetermine the current date twice for each row (which I believe wouldhappen at least).


|||Thanks!
I'll try that out.
I can say that it looks more efficient than my previous query!
Thanks again!

Sunday, February 12, 2012

Calculating change of values between rows

Hello forum.

I have three columns in my table with the following datatypes:

Date - DateTime
Height - Decimal
Change_From_last_Height - Decimal

I am using "SQL Server 2005 Express Edition". I'm fairly new to SQL and would greatly appreciate any help or advice I can get.

The "date" column increases by an extra day in every new row and I then enter the new height of the plant. What I want to know is how I can get SQL server express to automatically enter the difference in height between the current row's height and that of the previous row.

Is it possible to automate the entry in the Change_From_Last_Height column in SQL?

Put another way, I know how to find the difference between two values in the same row but different columns, but how do I calculate the difference between values in adjacent Rows (ie. Rows next to each other)?

Thank you.

hi,

your design, to me, is not correct, as you should not store the actual preeceding height or delta, but you should only retrieve it as you already have that value in the "preeceding row"..

so, in my mind, you only need to add a "calculated column" to your projection, responsible for getting the actual preeceding value or the delta..

the design changes to something similar to

SET NOCOUNT ON; USE tempdb; GO CREATE TABLE dbo.Plants( Id int NOT NULL PRIMARY KEY, Name varchar(10) NOT NULL ); CREATE TABLE dbo.PlantsHeight ( Id int NOT NULL CONSTRAINT fk_PlantHeight$Has$Plant FOREIGN KEY REFERENCES dbo.Plants (Id), Date datetime, Height decimal(12,6) CONSTRAINT pk_PlantsHeight PRIMARY KEY (Id, Date) ); GO INSERT INTO dbo.Plants VALUES ( 1, 'Plant 1' ); INSERT INTO dbo.Plants VALUES ( 2, 'Plant 2' ); INSERT INTO dbo.Plants VALUES ( 3, 'Plant 3' ); INSERT INTO dbo.PlantsHeight VALUES ( 1, '20070101', 10 ); INSERT INTO dbo.PlantsHeight VALUES ( 1, '20070102', 11 ); INSERT INTO dbo.PlantsHeight VALUES ( 1, '20070103', 12 ); INSERT INTO dbo.PlantsHeight VALUES ( 1, '20070104', 13 ); INSERT INTO dbo.PlantsHeight VALUES ( 1, '20070105', 14 ); INSERT INTO dbo.PlantsHeight VALUES ( 2, '20070101', 10 ); INSERT INTO dbo.PlantsHeight VALUES ( 2, '20070102', 10.3 ); INSERT INTO dbo.PlantsHeight VALUES ( 2, '20070103', 11.2 ); INSERT INTO dbo.PlantsHeight VALUES ( 2, '20070104', 11.9 ); INSERT INTO dbo.PlantsHeight VALUES ( 2, '20070105', 12 ); GO SELECT p.Name, ph.Date, ph.Height, (SELECT TOP (1) h.Height FROM dbo.PlantsHeight h WHERE h.Id = ph.Id AND h.Date < ph.Date ORDER by h.Date DESC) AS [SubQuery Preceeding Height], ph.Height - ISNULL((SELECT TOP (1) h.Height FROM dbo.PlantsHeight h WHERE h.Id = ph.Id AND h.Date < ph.Date ORDER by h.Date DESC), ph.Height ) AS [SubQuery Difference] FROM dbo.Plants p JOIN dbo.PlantsHeight ph ON p.Id = ph.Id ORDER BY p.Id, ph.Date; GO DROP TABLE dbo.PlantsHeight, dbo.Plants; --<- Name Date Height SubQuery Preceeding Height SubQuery Difference - -- -- -- - Plant 1 2007-01-01 00:00:00.000 10.000000 NULL 0.000000 Plant 1 2007-01-02 00:00:00.000 11.000000 10.000000 1.000000 Plant 1 2007-01-03 00:00:00.000 12.000000 11.000000 1.000000 Plant 1 2007-01-04 00:00:00.000 13.000000 12.000000 1.000000 Plant 1 2007-01-05 00:00:00.000 14.000000 13.000000 1.000000 Plant 2 2007-01-01 00:00:00.000 10.000000 NULL 0.000000 Plant 2 2007-01-02 00:00:00.000 10.300000 10.000000 0.300000 Plant 2 2007-01-03 00:00:00.000 11.200000 10.300000 0.900000 Plant 2 2007-01-04 00:00:00.000 11.900000 11.200000 0.700000 Plant 2 2007-01-05 00:00:00.000 12.000000 11.900000 0.100000

where the data is retrieved via a simple subquery using a TOP(1) tiebraker ordered by Date in descending order... you could use other semijoin techinque to avoid the top(1), but this is very simple.. and the required data is materialized on the fly without denormalizing the data design, and, should you "modify" an older value, you do not have to worry about modifying successive rows.. the normalization prevents this kind of "errors" that can lead you insane once you have thousands of rows..

regards

|||

Wow! Andrea, you're a life saver!

Thank you! Thank you! Thank you! This problem had me really nervous and you wound up contributing a more intensive solution than I could have possibly asked for.

Once again, thanks a lot, I'll try it out in a moment.

Calculating and storing alternative calender/dates

Hi Engine room.

I want to automatically populate an alternative date column with hijri (Arabic) dates. So I will have two date columns in my datawarehouse table, one is for gregorian dates, the other for the equivalent in Hijri - a bilingual date system if you like. Now I guess I could do it in the SSI ETL tool and use Julian Dates, but the problem is storing the resulting value. - what data type should I use for hijri dates?

The dates can be input by the user in either format, which means the alternate date has to be populated.

Eventually I hope to make a bilingual system, I don't understand the user-defined types or how to define them, but I suspect they could be used in someway to help. Why am I doing this? - well eventually I hope to populate a cube for analysis and deliver a dual-language-dashboard using the new CTP3 stuff.

Any suggestions on how I can make this dual-date system? - with a view to making a bilingual system eventually.

adv(thnx)ance..Mark.

HijriCalendar is one of the Calendars defined in the .NET FCL(framewor. class library) so you can use either DateTime or INT to store it. The actual calulation start with MSDN Middleeast to see if code exist for it if not you have to look for code to do it. The links below will take you in the right direction.

http://authors.aspalliance.com/aspxtreme/sys/globalization/HijriCalendarClass.aspx

http://www.microsoft.com/globaldev/getWR/steps/wrg_clndr.mspx

http://www.microsoft.com/middleeast/msdn/