Showing posts with label time. Show all posts
Showing posts with label time. Show all posts

Friday, March 30, 2012

How to rename a database?

hi

every time I try to rename my database I face an error

I want to rename the database file phisically not just changing logigal name with

Alter Database <database name> modify name command

please step by step tell me what to do

whether with using TSql or Managment Studio

thanks

detach the database

rename the files

then "attach as" new database name

sql

How to rename a database?

hi

every time I try to rename my database I face an error

I want to rename the database file phisically not just changing logigal name with

Alter Database <database name> modify name command

please step by step tell me what to do

whether with TSql or Managment Studio

thanks

Workaround.

1. Deattach database files.
2. Rename physical files.
3. Attaching database files again and specify names you want.

you can do all this from SQL Management Studio 2005.

- Jignesh Desai

|||

Best way to do bit Your problem:

Use command:

sp_renamedb <old_name>, <new_name>

That's all. ;)

How to rename a database?

hi

I want to rename the phisical file of the dabase for instance rename <MyDatabase.mdf> to <Renameddatabase.mdf>

every time I do so whether directly renamin the file or by

using Alter Database command I face an error

note that I don't want to logically rename the database

please tell me step by step what to do

thanks in advance

Easiest way is to take a backup of your existing database and restore it with renaming the mdf files. Have you read the books online (help file)?

Are any users (other than yourself) connected to the database while you try to rename the file?

ALTER DATABASE database_name MODIFY FILE ( NAME = logical_name , FILENAME = 'new_path\os_file_name' )Have you tried this command?

How to remove WITH FILLFACTOR = 100 when Generate Sql Script ?

Hello,

I'm using Entreprise Manager (for Sql Server 2000) to generate my
database's script. By mistake, i've changer FillFactor one time. And,
now I can't remove this data from generated sql script. How to remove
that ?

Thank's a lot.rabii (rabii.mail@.gmail.com) writes:
> I'm using Entreprise Manager (for Sql Server 2000) to generate my
> database's script. By mistake, i've changer FillFactor one time. And,
> now I can't remove this data from generated sql script. How to remove
> that ?

Can't you just run the file through a search/replace session in some
text editor? Then you could build a new database, and then script
from that one.

Even better, have all your SQL code under version control, so you
don't have to script from the databaes.

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

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||Thanks for reply :),

I know this solutions :), but, the problem that I have a production
database. For each new version of my product, I have to compare my new
database schema and the old one (current production database). So the
tool "Sql Server Compare" (by comparing the databases script) show me
always that all the table are different although the difference is
simply the FILLFACTOR (in production database). Now I can change it
using Entreprise Manager but I can't remove it ?|||If that's Red-Gate's SQL Compare, I think that there is an option to
ignore fillfactors, among other things. Unfortunately, I'm at a machine
that doesn't have that tool installed, so I can't confirm that. I know
that you can definitely ignore some things, and I *think* that
FILLFACTOR is one of them.

Good luck,
-Tom.|||rabii (rabii.mail@.gmail.com) writes:
> I know this solutions :), but, the problem that I have a production
> database. For each new version of my product, I have to compare my new
> database schema and the old one (current production database). So the
> tool "Sql Server Compare" (by comparing the databases script) show me
> always that all the table are different although the difference is
> simply the FILLFACTOR (in production database). Now I can change it
> using Entreprise Manager but I can't remove it ?

So where is the fill factor wrong? In the development database or in
the production database? But whichever, can't you just adapt the
fillfactor of the development database to the production database?

Then again, fill factor is one of these things that could be different
from database to database, because different instances of the schema
has different data load. So you should probably see if your comparison
tool can ignore difference in fill factor.

Finally, I can't keep from saying that the whole thing of comparing
database schemas to build change scripts is not a very good idea. Do
you really want all sort of test junk in the dev database hit the
production server? If you have your code under version control,
you can build change scripts from the version-control system. This
gives you a much more solid base to stand on.

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

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||thanks again for every one :)

I've said that I'm using the tool "Sql Server Compare" (it's a free
tool).

You're right when you said that it is better to use a version control
solution. But now the problem, that by mistake, I've added fillfactor =
x in the production database. In the dev database, I havn't did that.
When I compare the two databases, I notice that the comprator (sql
server compare) show me that all the table are different. When I
analyse the code, simply the fill factor is not the same. I can resolve
that by adding the same fillfactor in my dev database but I wan't to
know " if there is a way by script to remove fillfactor = x" ?|||rabii (rabii.mail@.gmail.com) writes:
> I've said that I'm using the tool "Sql Server Compare" (it's a free
> tool).
> You're right when you said that it is better to use a version control
> solution. But now the problem, that by mistake, I've added fillfactor =
> x in the production database. In the dev database, I havn't did that.
> When I compare the two databases, I notice that the comprator (sql
> server compare) show me that all the table are different. When I
> analyse the code, simply the fill factor is not the same. I can resolve
> that by adding the same fillfactor in my dev database but I wan't to
> know " if there is a way by script to remove fillfactor = x" ?

For an index you should be able to get rid of with with CREATE INDEX ...
WITH DROP_EXISTING. If it's a PRIMARY KEY constraint of a UNIQUE constraint,
I think you have to drop and recreate. Since you typically have FK
constraints to a PK, that can be kind of messy.

I played around a little, and it seems that Enterprise Manager does not
include fillfactor for primary keys, so changing your dev database may
not help.

Looks as if you either have to rebuild the production database or give
SQL Server Compare the boot...

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

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

How to remove time from date?

Hello,
I have a table (T1) that has a field that holds a date with a time. In
another table (T2) I have records related to T1 on an ID field (one T1 to
many T2). T2 has a date field also, but this field does not have time (ie
the time part is midnight). I want to join the two tables on the ID and
Date but the time portions of the dates are not equal so they do not match.
SELECT T1.ID, T2.Date, T2.Value
FROM T1
JOIN T2
ON T1.ID = T2.ID AND T1.Date = T2.Date
Does anyone know how I can set the time portion of T1.Date to midnight in
the query (not in the table) so the join will work.
I've tried CONVERT(DATETIME, T1.Date, 106) but it keeps the time part. I
want the time part dropped or midnight.
Thanks
EdmundHi,
Try this...
SELECT T1.ID, T2.Date, T2.Value
FROM T1
JOIN T2
ON T1.ID = T2.ID AND Convert(varchar(13), T1.Date, 112) = Convert
(Varchar(13), T2.Date, 112)
HTH
Barry|||I don't know why I did not think of this. It was staring right at me.
Thanks Barry. I've gone for CONVERT(CHAR(10),T1.Date, 120)) as it will
implicitly convert to DATETIME with date as midnight.
Edmund.
"Barry" <barry.oconnor@.manx.net> wrote in message
news:1149517628.941905.154220@.h76g2000cwa.googlegroups.com...
> Hi,
> Try this...
> SELECT T1.ID, T2.Date, T2.Value
> FROM T1
> JOIN T2
> ON T1.ID = T2.ID AND Convert(varchar(13), T1.Date, 112) = Convert
> (Varchar(13), T2.Date, 112)
>
> HTH
> Barry
>|||try this:
CONVERT(VARCHAR(10), T1.date, 126)
Barry wrote:
> Hi,
> Try this...
> SELECT T1.ID, T2.Date, T2.Value
> FROM T1
> JOIN T2
> ON T1.ID = T2.ID AND Convert(varchar(13), T1.Date, 112) = Convert
> (Varchar(13), T2.Date, 112)
>
> HTH
> Barry|||Edmund,
You might want to chk this article :: http://www.aspfaq.com/show.asp?id=2460
Extract from that article:
--
For example, to get today's date in YYYYMMDD format, you currently need to
call the following:
SELECT CONVERT(CHAR(8), GETDATE(), 112)
What does the 112 mean? Nothing. It's just an arbitrary number representing
this specific format.
Best Regards
Vadivel
http://vadivel.blogspot.com
"Edmund" wrote:

> Hello,
> I have a table (T1) that has a field that holds a date with a time. In
> another table (T2) I have records related to T1 on an ID field (one T1 to
> many T2). T2 has a date field also, but this field does not have time (ie
> the time part is midnight). I want to join the two tables on the ID and
> Date but the time portions of the dates are not equal so they do not match
.
> SELECT T1.ID, T2.Date, T2.Value
> FROM T1
> JOIN T2
> ON T1.ID = T2.ID AND T1.Date = T2.Date
> Does anyone know how I can set the time portion of T1.Date to midnight in
> the query (not in the table) so the join will work.
> I've tried CONVERT(DATETIME, T1.Date, 106) but it keeps the time part. I
> want the time part dropped or midnight.
> Thanks
> Edmund
>
>|||Edmund,
To truly remove time from datetime and not just "hide" it:
SELECT CAST(DATEDIFF(DAY,0,getDate()) AS DATETIME)
Returns:
2006-06-06 00:00:00.000
Mark|||A slightly better way to do it than using the CONVERT() function calls
would be:
SELECT T1.ID, T2.Date, T2.Value
FROM T1
INNER JOIN T2
ON T1.ID = T2.ID
AND DATEADD(d, DATEDIFF(d, 0, T1.Date), 0) = DATEADD(d,
DATEDIFF(d, 0, T2.Date), 0)
If you want more info on it, Tibor Karaszi wrote a pretty good web
article about datetime data including a short section on stripping time
info:
http://www.karaszi.com/SQLServer/in...idOfTimePortion
*mike hodgson*
http://sqlnerd.blogspot.com
Barry wrote:

>Hi,
>Try this...
> SELECT T1.ID, T2.Date, T2.Value
> FROM T1
> JOIN T2
> ON T1.ID = T2.ID AND Convert(varchar(13), T1.Date, 112) = Convert
>(Varchar(13), T2.Date, 112)
>
>HTH
>Barry
>
>|||Mike, this is very good.
"Mike Hodgson" <e1minst3r@.gmail.com> wrote in message news:u4N4C8PiGHA.1612@.
TK2MSFTNGP04.phx.gbl...
A slightly better way to do it than using the CONVERT() function calls would
be:
SELECT T1.ID, T2.Date, T2.Value
FROM T1
INNER JOIN T2
ON T1.ID = T2.ID
AND DATEADD(d, DATEDIFF(d, 0, T1.Date), 0) = DATEADD(d, DATEDIFF(d, 0, T2.Da
te), 0)
If you want more info on it, Tibor Karaszi wrote a pretty good web article a
bout datetime data including a short section on stripping time info:
http://www.karaszi.com/SQLServer/in...idOfTimePortion
mike hodgson
http://sqlnerd.blogspot.com
Barry wrote:
Hi,
Try this...
SELECT T1.ID, T2.Date, T2.Value
FROM T1
JOIN T2
ON T1.ID = T2.ID AND Convert(varchar(13), T1.Date, 112) = Convert
(Varchar(13), T2.Date, 112)
HTH
Barry

Friday, March 23, 2012

How to reflect the equivalent of the relational IN operator in MDX

I need to filter a set, based in another attribute hierarchy.

So I am looking for something like

filter(Time.Months.children , Time.Months.currentmember.label in ({Timen.MonthName.Children})

The list is generated dinamycally, so the OR approach wouldn't work (unless I write 12 expressions.

Any ideas ?

Thank you

Alejandro Leguizamo

SQL Server MVP

Could you give an example with data, to help clarify? If this is a case where dimensions [Time] and [Timen] have identical structure (eg: role-playing dimensions like Date and ShipDate in Adventure Works), and you want the set in [Time].[Months] hierarchy, equivalent to some set in [Timen].[Months], then LinkMember() may work, like:

Generate([TimenSet], {LinkMember([Timen].[Month].CurrentMember, [Time].[Month])})

How to refer to the whole cube while using the filter of the cube browser?

Hello!

I've got an accounting cube with balances as measures and amongst others a time dimension. There's also a calculated member which should show the balance of the previous year. This calculated member uses the PARALLELPERIOD-function.

So far everything works fine! But while using the filter of the cube browser and selecting a certain year, I can't refer to other years than the selected year.

So how can I get the balance of the previous year?

Thanks for any help!

From the information you provided I infer that the calculated member is defined inside your Time hierarchy. The solution to your problem could be one of the following:

1. Define your calculated member in a separate dimension, you can call it [Time Series] for example.

2. Alternatively, do not put Time hierarchy into the Filter of the cube browser, put it on Rows or Columns instead, and then filter only the current year and the calculated member.

3. Instead of calculated member use a calculated measure.

|||

Hello Tigran!

Thanks for you advice! But I defined the calculated member inside the Measure Group. So I think that it's called calculated measure. Am I right? So do you know any solution in this case?

I have to use the filter of the cube browser, because I have to use this kind of filter also in the KPI's! There's no alternative.

|||

Yes, it is a calculated measure in that case.

I think the complete answer to your question would depend on what client tools you will use to display all this data (or in case of reporting website - the application suite used to create the reports). Every application can have its own method of querying for the data, including the Cube browser inside BI Development Studio.

In your particular case (using Cube Browser) try to drag your Time hierarchy in a small spot that says 'Drop Filter Fields here'. It may give you a different behavior.

If that turns out to fix the problem, I would say that the original problem is likely to be caused by Cube Browser's use of Subcubes to restrict the data to a particular slice of the cube. Alternative query method using WHERE clause of MDX may give you different results.

|||

Yes, you're right. If I drag the Time hierarchy into 'Drop Filter Fields here', the calculated measure works properly.

But as I don't know so far which client tool I'll use, I want to fix the problem caused by the filter of the cube browser.

My intention is to refer to the whole cube (and not to any slice) within the MDX statement.

Now the statement looks like that:

CREATE MEMBER CURRENTCUBE.[MEASURES].LastYearBalance

AS

(

[Measures].[Balance],

PARALLELPERIOD

(

[Time].[Hierarchy].Levels(1),

1,

[Time].[Hierarchy].CurrentMember

)

),

VISIBLE = 1;

So is there any possibility to add a statement which makes a reference to the whole cube?

I think about creating something like a Session Cube and then refering to this Session Cube within my MDX statement!

But neither I don't know how to do that within the MDX skript nor if it's possible.

|||

I wish there was such statement indeed!

Unfortunately, I don't think there is anything you can do to make your calculation statement more 'correct'. The only bulletproof solution is having a regular measure (not a calculated one), that carries last year's data. For that, you will need to modify the underlying relational database.

But I would recommend studying what client tools will be used first. Because you may find that this is not even an issue with a lot of existing applications out there (as most of them use WHERE clause for stuff you put in Filter area). For example, OWC should work just fine.

|||

Ok, there seems to be no solution which makes my calculated measure working properly.

Right now I'm testing a beta version of Excel 2007 as BI frontend tool to see how it deals with this problem.

Thank you very much for help!

Wednesday, March 21, 2012

How to reduce the time when using a variable

Hi,

I have a table with column value like '123 345 678 143 648' like that. What I need to do is I have to take each code value and put it as a new record in another table. So, if I say 'Select substring(column_name,1,3) from table' then it is very fast (fraction of second). But since I need to take each code and the # of codes in each record may vary, I am using a while loop to take each code and so I delclared a variable @.i and now my select statement is like this: 'Select substring(column_name,@.i,3) from table'. Interesting now this select statement is taking almost 2 mins for each iteration.

Why it is like this? Is there any way I can reduce the time taken to execute each iteration?

Thanks.

how many records of this kind are you processing.

the number of records must ne put into consideration.

a cursor that iterate with every records first must be put in place

then place the while loop inside every fetch of the cursor

do the processing(while loop) of the column

i think there should be two loops to handle this case.

one that iterates with the records

and one that iterates for every codes in the the column.

if this is an SP. a with recompile option will make your query faster

regards.

|||

What about

INSERT INTO table1

SELECT SUBSTRING(column_name,1,3) from table WHERE SUBSTRING(column_name,1,3) <> ''

UNION

SELECT SUBSTRING(column_name,4,3) from table WHERE SUBSTRING(column_name,4,3) <> ''

UNION

...

? Copy/paste above line until substring index matches column_name size; or, if you don't want to hardcode it - construct this query referring to column_name size and run it through EXEC.

This could be faster - try it out...

|||

If you are using SQL Server 2005 then you can do the following:

1. Create a table-valued function that takes a string and splits it based on space character. You can search the web for several sample functions that does this operation

2. Use it in a SELECT statement using APPLY operator like:

insert into tbl(i, ...)

select s.val

from table as t

cross apply splitstr(t.column_name) as s

In SQL Server 2000, you can do similar operation except there is no APPLY operator so you cannot use a TVF. You can use a table of numbers to split the string and then do a cross join with this table instead. Or the approach using UNION as suggested in another post will also work. Make sure you use UNION ALL though for better performance and to eliminate the unnecessary sorting.

|||Here is an article on handling arrays and lists - quite a few methods and instruments, may be useful.|||

Hi Umachandar,

Your tip was very helpful to me. Now the whole process completes in 2 mins. Thx.

sql

Friday, March 9, 2012

How to Read The MSDTC LOG.

Hello,
We have an application which uses DTC they are seeing some errors in the
application log and at the same time they want to see if there are any errors
in the MSDTC log but i am not sure how to open the file and with what .it
seems like
text file but when i open it i can't read it .is there anything i should do
Thanks ....
The log file is encrypted and the format is not publicly
available. The files are just used by DTS to manage
transactions and aren't really meant for viewing outside of
what the service itself reads and uses.
Errors with the service itself should show up in the windows
event logs. You may also want to check the RPC service and
make sure you don't have any errors with that as DTS depends
on and uses this service. Overall though, you may be better
off posting the errors you are seeing and going from there.
-Sue
On Thu, 18 Nov 2004 13:49:13 -0800, "chinn"
<chinn@.discussions.microsoft.com> wrote:

>Hello,
>We have an application which uses DTC they are seeing some errors in the
>application log and at the same time they want to see if there are any errors
>in the MSDTC log but i am not sure how to open the file and with what .it
>seems like
>text file but when i open it i can't read it .is there anything i should do
>Thanks ....
|||Oops...those references should be DTC not DTS.
-Sue
On Thu, 18 Nov 2004 17:12:55 -0700, Sue Hoegemeier
<Sue_H@.nomail.please> wrote:
[vbcol=seagreen]
>The log file is encrypted and the format is not publicly
>available. The files are just used by DTS to manage
>transactions and aren't really meant for viewing outside of
>what the service itself reads and uses.
>Errors with the service itself should show up in the windows
>event logs. You may also want to check the RPC service and
>make sure you don't have any errors with that as DTS depends
>on and uses this service. Overall though, you may be better
>off posting the errors you are seeing and going from there.
>-Sue
>On Thu, 18 Nov 2004 13:49:13 -0800, "chinn"
><chinn@.discussions.microsoft.com> wrote:

How to Read The MSDTC LOG.

Hello,
We have an application which uses DTC they are seeing some errors in the
application log and at the same time they want to see if there are any errors
in the MSDTC log but i am not sure how to open the file and with what .it
seems like
text file but when i open it i can't read it .is there anything i should do
Thanks ....The log file is encrypted and the format is not publicly
available. The files are just used by DTS to manage
transactions and aren't really meant for viewing outside of
what the service itself reads and uses.
Errors with the service itself should show up in the windows
event logs. You may also want to check the RPC service and
make sure you don't have any errors with that as DTS depends
on and uses this service. Overall though, you may be better
off posting the errors you are seeing and going from there.
-Sue
On Thu, 18 Nov 2004 13:49:13 -0800, "chinn"
<chinn@.discussions.microsoft.com> wrote:
>Hello,
>We have an application which uses DTC they are seeing some errors in the
>application log and at the same time they want to see if there are any errors
>in the MSDTC log but i am not sure how to open the file and with what .it
>seems like
>text file but when i open it i can't read it .is there anything i should do
>Thanks ....|||Oops...those references should be DTC not DTS.
-Sue
On Thu, 18 Nov 2004 17:12:55 -0700, Sue Hoegemeier
<Sue_H@.nomail.please> wrote:
>The log file is encrypted and the format is not publicly
>available. The files are just used by DTS to manage
>transactions and aren't really meant for viewing outside of
>what the service itself reads and uses.
>Errors with the service itself should show up in the windows
>event logs. You may also want to check the RPC service and
>make sure you don't have any errors with that as DTS depends
>on and uses this service. Overall though, you may be better
>off posting the errors you are seeing and going from there.
>-Sue
>On Thu, 18 Nov 2004 13:49:13 -0800, "chinn"
><chinn@.discussions.microsoft.com> wrote:
>>Hello,
>>We have an application which uses DTC they are seeing some errors in the
>>application log and at the same time they want to see if there are any errors
>>in the MSDTC log but i am not sure how to open the file and with what .it
>>seems like
>>text file but when i open it i can't read it .is there anything i should do
>>Thanks ....

How to Read The MSDTC LOG.

Hello,
We have an application which uses DTC they are seeing some errors in the
application log and at the same time they want to see if there are any error
s
in the MSDTC log but i am not sure how to open the file and with what .it
seems like
text file but when i open it i can't read it .is there anything i should do
Thanks ....The log file is encrypted and the format is not publicly
available. The files are just used by DTS to manage
transactions and aren't really meant for viewing outside of
what the service itself reads and uses.
Errors with the service itself should show up in the windows
event logs. You may also want to check the RPC service and
make sure you don't have any errors with that as DTS depends
on and uses this service. Overall though, you may be better
off posting the errors you are seeing and going from there.
-Sue
On Thu, 18 Nov 2004 13:49:13 -0800, "chinn"
<chinn@.discussions.microsoft.com> wrote:

>Hello,
>We have an application which uses DTC they are seeing some errors in the
>application log and at the same time they want to see if there are any erro
rs
>in the MSDTC log but i am not sure how to open the file and with what .it
>seems like
>text file but when i open it i can't read it .is there anything i should do
>Thanks ....|||Oops...those references should be DTC not DTS.
-Sue
On Thu, 18 Nov 2004 17:12:55 -0700, Sue Hoegemeier
<Sue_H@.nomail.please> wrote:
[vbcol=seagreen]
>The log file is encrypted and the format is not publicly
>available. The files are just used by DTS to manage
>transactions and aren't really meant for viewing outside of
>what the service itself reads and uses.
>Errors with the service itself should show up in the windows
>event logs. You may also want to check the RPC service and
>make sure you don't have any errors with that as DTS depends
>on and uses this service. Overall though, you may be better
>off posting the errors you are seeing and going from there.
>-Sue
>On Thu, 18 Nov 2004 13:49:13 -0800, "chinn"
><chinn@.discussions.microsoft.com> wrote:
>

Friday, February 24, 2012

How to query this?

Hello,
Long time I am puzzled over the following task. This problem should be
similar to many systems, and it would be interesting to know what are best
practices to solve this.
The setup:
Table, that contains log of events. Typical fields would be: 1) uniqueID; 2)
evtTime; 3)evtType. Then there are some additional fields that carry
additional logged event data.
Sample data:
ID evtTime evtType
1 10-11-2005 A
2 13-11-2005 B
3 20-11-2005 C
4 22-11-2005 B
Now, if I want to perform analysis on this data, typical need would be to
analyze sequence of event types. In the sample data above, the sequence is
A-B-C-B (ordering by date-time). I find it very complex to create a query
that would let me find sequence of events by given pattern.
For example, I could use query to discover the next element in sequence and,
thus, use this expression for querying:
SELECT evtType, (SELECT TOP 1 evtType FROM SampleData WHERE
evtTime>Level1.evtTime ORDER BY logDate) AS nextType FROM SampleData AS
Level1
It would be possible to extract also the second next event type in sequence
in similar fashion, but I am afraid that the complexity of the overall query
would be unreasonable and performance would be slow. Plus, if I want also,
for example, count days when the "event type A was in force", I need to add
nex subquery for the evtTime:
SELECT evtType, evtTime, (SELECT TOP 1 evtType FROM SampleData WHERE
evtTime>Level1.evtTime ORDER BY logDate) AS nextType, (SELECT TOP 1 evtTime
FROM SampleData WHERE evtTime>Level1.evtTime ORDER BY logDate) AS nextTime
FROM SampleData AS Level1
Only then I could find the sequences that, for example, have "event A in
force at least 10 days, then followed by event B, and then by C".
How this standard need could be solved so that I don't need to create large
temporary tables, populated with data by raw code?
PavilsOn Tue, 15 Nov 2005 16:30:55 +0200, Pavils Jurjans wrote:
(snip)
>The setup:
>Table, that contains log of events. Typical fields would be: 1) uniqueID; 2
)
>evtTime; 3)evtType. Then there are some additional fields that carry
>additional logged event data.
>Sample data:
>ID evtTime evtType
>1 10-11-2005 A
>2 13-11-2005 B
>3 20-11-2005 C
>4 22-11-2005 B
>Now, if I want to perform analysis on this data, typical need would be to
>analyze sequence of event types. In the sample data above, the sequence is
>A-B-C-B (ordering by date-time). I find it very complex to create a query
>that would let me find sequence of events by given pattern.
(snip)
>Only then I could find the sequences that, for example, have "event A in
>force at least 10 days, then followed by event B, and then by C".
Hi Pavils,
If this is your typical reporting need, then I recommend that you
transform the data from events to durations (or states, or whatever term
is appropriate in your case).
CREATE TABLE Durations
(StartDate smalldatetime NOT NULL,
EndDate smalldatetime DEFAULT NULL,
EventType char(1) NOT NULL,
PRIMARY KEY (StartDate),
UNIQUE (EndDate),
FOREIGN KEY (EndDate) REFERENCES Durations (StartDate),
CHECK(EndDate > StartDate)
)
In most cases, I'd make Durations a view instead of a table. This might
well be an exception to that rule. The view could be slow, since it
would require a self-join. If your queries would then involve joining
the view to itself, you'd effectively be joining the base table to an
exponential increasing number of copies of itself.
Durations as indexed view would be ideal, but I don't think it's
possible to write a query that computes the Durations correctly without
breaking the limitations for indexed views.
That leaves you with two options for how to populate the table:
1. Remove the Events table; change the stored procedure or front-end
code that currently popultes the Events table to make the correct
changes to the Durations table, or
2. Keep the Events table; leave front-end and stored procedures
unchanges, but add insert, update and delete triggers on the Events
table to copy over all changes to the Durations table.
Once you have the Durations table, the query you give in your final
example would be:
SELECT d1.StartDate, d2,StartDate, d3.StartDate, d3.EndDate
FROM Durations AS d1
INNER JOIN Durations AS d2
ON d2.StartDate = d1.EndDate
INNER JOIN Durations AS d3
ON d3.StartDate = d2.EndDate
WHERE d1.EndDate >= DATEADD(day, 10, d1.StartDate)
AND d1.EventType = 'A'
AND d2.EventType = 'B'
AND d3.EventType = 'C'
Best, Hugo
--
(Remove _NO_ and _SPAM_ to get my e-mail address)|||Thanks, Hugo for you input.
I studied it carefully. To extend my proposed sample to my real case, I must
add that the events are registered for large number of subjects, so the
events table also has reference to subject ID. Your query then could look
like
SELECT d1.StartDate, d2,StartDate, d3.StartDate, d3.EndDate
FROM Durations AS d1
INNER JOIN Durations AS d2
ON d2.StartDate = d1.EndDate AND d2.subID=d1.subID
INNER JOIN Durations AS d3
ON d3.StartDate = d2.EndDate AND d3.subID=d2.subID
WHERE d1.EndDate >= DATEADD(day, 10, d1.StartDate)
AND d1.EventType = 'A'
AND d2.EventType = 'B'
AND d3.EventType = 'C'
Perhaps that just adds another load to the view. Building a temp table could
be solution for some standard reports, but the data are updated every minute
and some reports are asking another criteria on the series, so perhaps view
or dynamically generated query, while potentially slow, could be the most
realistic alternative.
However, I am now a bit worried that it seems that theoretically there could
be cases when the dates of succeeding events could be identical, so
apparently I need another order field. It seems that the best (could easily
be used for self-joins) would be carrying reference to previous event ID,
but it involves difficulty how to order the events in the right order by
simple SQL server means. The only option left then is a clumsy "orderNumber"
that will be a hassle to populate and it will be even hasslier to insert a
new event in existing series. Lots of code will be required to keep that
structure intact with no errors in numeration. Perhaps I need to weigh how
much I need a query that would give ordered list of events vs doing this
ordering by code.
Another concern is making self-joins vs using subqueries. I could get the
fields from succeeding event quite easily, and also getting fields from next
succeeding event seems no problem. The question is only about how effective
is this. Perhaps only tests will show this. I am sort of dismayed that so
few tools are built in MSSQL to analyse record series - that is typical need
in complex analysis and caching all the analysis sample in application
memory for proprietary code analysis sometimes is very ineffective.
Regards,
Pavils Jurjans|||On Mon, 21 Nov 2005 19:37:59 +0200, Pavils Jurjans wrote:

>Thanks, Hugo for you input.
>I studied it carefully. To extend my proposed sample to my real case, I mus
t
>add that the events are registered for large number of subjects, so the
>events table also has reference to subject ID. Your query then could look
>like
>SELECT d1.StartDate, d2,StartDate, d3.StartDate, d3.EndDate
>FROM Durations AS d1
>INNER JOIN Durations AS d2
> ON d2.StartDate = d1.EndDate AND d2.subID=d1.subID
>INNER JOIN Durations AS d3
> ON d3.StartDate = d2.EndDate AND d3.subID=d2.subID
>WHERE d1.EndDate >= DATEADD(day, 10, d1.StartDate)
>AND d1.EventType = 'A'
>AND d2.EventType = 'B'
>AND d3.EventType = 'C'
Hi Pavils,
Yes, that's how you would change it. I'd probably also add the subject
to the SELECT clause.

>Perhaps that just adds another load to the view.
Depends. With the right indexes it *might* even speed things up.

> Building a temp table could
>be solution for some standard reports, but the data are updated every minut
e
>and some reports are asking another criteria on the series, so perhaps view
>or dynamically generated query, while potentially slow, could be the most
>realistic alternative.
Yes.
But if that's to slow, then consider permanently storing both the
beginning and the end of the events. There are various ways to do this:
1. Change it in whatever currently produces the data.
2. Use a stored procedure to handle insertions; add code to that SP to
fill the end date of the "previous" event.
3. Create a trigger on the table that will populate end dates as
appropriate.

>However, I am now a bit worried that it seems that theoretically there coul
d
>be cases when the dates of succeeding events could be identical, so
>apparently I need another order field.
Or you could store the time in addition to the date. The smalldatetime
datatype stores date + time with a precision of minutes; the datetime
datatype even has a precision of 3/1000th of a second.

>It seems that the best (could easily
>be used for self-joins) would be carrying reference to previous event ID,
If you choose that, then remove the the end date. I included that to
serve as a reference to the previous event. If you use a different
reference, there's no need to keep the end date.
However, don't ever rely on a system-generated identifier to serve as
the only key for a table. If the "real" key is clumsy, you can add a
system-generated identifier to serve as a "surrogate" key.

>but it involves difficulty how to order the events in the right order by
>simple SQL server means.
Are the events inserted in chronological order? In that case, it's quite
easy to have the system generate an ID value that will keep increasing.
That would make ordering trivial.
(snip)
> I am sort of dismayed that so
>few tools are built in MSSQL to analyse record series - that is typical nee
d
>in complex analysis and caching all the analysis sample in application
>memory for proprietary code analysis sometimes is very ineffective.
You might want to investigate Analysis Services. I must admit that the
only thing I know about it is it's name (in some circles, that's enough
to qualify as "expert"...). But who knows - maye it's just the tool for
your needs!
Best, Hugo
--
(Remove _NO_ and _SPAM_ to get my e-mail address)

Sunday, February 19, 2012

How to query dates

How can I query date only in a where clause and not include the time part? When I use the where below if the time part of the date entry has past then the rows are not returned.

WHERE A.Selected=1 AND A.EndDate Is Null OR A.Enddate >= GETDATE()

Thanks,there are convert functions with codes like 410,411...etc am not xactly sure which one it is..may be if yo google around you can get the snippet of code...
another way you can also try


WHERE A.Selected=1 AND A.EndDate Is Null OR
(
datepart(m,A.Enddate) >= datepart(m,GETDATE()) and
datepart(d,A.Enddate) >= datepart(d,GETDATE()) and
datepart(y,A.Enddate) >= datepart(y,GETDATE())
)

hth