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

Wednesday, March 28, 2012

How can I compare datetime in a query?

I have a table with the following columns

company_Id employee_id logon_time_id logoff_time start_valid_period end_valid_period

Employee's working time should only be counted if it is between start_valid_period and end_valid_period

So, if I have for employee1 from company1

logon_time_id = 04/07/2006 11:00
loggoff_time = 04/07/2006 12:20
start_valid_period = 04/07/2006 12:10
end_valid_period = 04/07/2006 12:30

I should consider 04/07/2006 12:10 as the initial datetime, 04/07/2006 12:20 as the final datetime, and count only 10min of work to him. In code:

if(logon_time_id < start_valid_period) initialDatetime = start_valid_period else initialDatetime = logon_time_id

if(logoff_time < end_valid_period) finalDatetime = logoff_time else finalDatetime = end_valid_period

Is there anyway I can do this in a query, without using a stored procedure with "ifs" and everything else?

Thank you!

Hi!

Forget one thing! I'm wondering if there is a way of doing it without using the case statement as well!

Thank you!

|||

use datediff

http://msdn2.microsoft.com/en-us/library/ms189794.aspx

the case keyword in sql is very powerful you can use it in the query to replace value

this is a single select statement to solve your problem

select

datediff( mi,

case
when logon_time_id< start_valid_period then start_valid_period
else logon_time_id
end

,-- comma
case
when loggoff_time > end_valid_period then end_valid_period
else loggoff_time
end

)as minutesworked

from mytime

joeydj

|||

use datediff

http://msdn2.microsoft.com/en-us/library/ms189794.aspx

the case keyword in sql is very powerful you can use it in the query to replace value

this is a single select statement to solve your problem

select

datediff( mi,

case
when logon_time_id< start_valid_period then start_valid_period
else logon_time_id
end

,-- comma
case
when loggoff_time > end_valid_period then end_valid_period
else loggoff_time
end

)as minutesworked

from mytime

joeydj

|||

Case would be easiest and clearest, but you could do:

select (select max(dateval)
from (select login_time_id as dateval
union all
select start_valid_period)) as initialDatetime,

(select min(dateval)
from (select logoff_time
union all
select end_valid_period)) as initialDatetime

from ...

|||

The first thing to note when comparing date overlaps is that there are 6 cases -- 4 with overlap and 2 without. Presumably, if the user was logged in only during a period that was not valid, the elapsed time should be zero. Using the logic as listed (ifs and CASEs) you could end up with a negative time accounting.

Now for a trick from the old days, before CASE was available (we always walked uphill barefoot a lot in those days, too ;) ). There is a function called SIGN() that returns -1, 0, or 1 depending on the sign of a number. By coercing it into a binary 1 or 0 and multiplying by it, you can get the same effect as a conditional.

In this case, the problem can be recast as increase the start_valid by the difference with the logon time as long as long as the difference is greater than zero. Similarly, the end_valid should be decreased by the difference of the logoff time as long as that difference is negative. Once these adjustments have been done, now apply the DateDiff().

Here is some code that should do the trick. As noted above, the case of no overlap is handled separately. The CASE statements are only to explain which case is being handled.

Drop Table #timekeeper
go

Create Table #timekeeper(
username varchar(30),
logon_time_id datetime,
loggoff_time datetime,
start_valid_period datetime,
end_valid_period datetime
)

Insert #timekeeper values( 'Fred', '04/07/2006 11:00', '04/07/2006 12:20', '04/07/2006 12:10', '04/07/2006 12:30' )
Insert #timekeeper values( 'Wilma', '04/07/2006 12:20', '04/07/2006 12:40', '04/07/2006 12:10', '04/07/2006 12:30' )
Insert #timekeeper values( 'Barney', '04/07/2006 11:20', '04/07/2006 12:40', '04/07/2006 12:10', '04/07/2006 12:30' )
Insert #timekeeper values( 'Betty', '04/07/2006 12:20', '04/07/2006 12:25', '04/07/2006 12:10', '04/07/2006 12:30' )
Insert #timekeeper values( 'Pebbles', '04/07/2006 11:00', '04/07/2006 11:25', '04/07/2006 12:10', '04/07/2006 12:30' )
Insert #timekeeper values( 'Bambam', '04/07/2006 12:35', '04/07/2006 12:50', '04/07/2006 12:10', '04/07/2006 12:30' )

Select username,
Datediff( mi,
DateAdd( ms, (( 1 + Sign( DateDiff( ms, start_valid_period, logon_time_id ) ) ) / 2) * DateDiff( ms, start_valid_period, logon_time_id ), start_valid_period ),
DateAdd( ms, (( 1 + Sign( DateDiff( ms, loggoff_time, end_valid_period ) ) ) / 2) * DateDiff( ms, end_valid_period, loggoff_time ), end_valid_period )
) as usage_minutes,
'Overlap',
Case when logon_time_id < start_valid_period then 'Logged on early' else 'Logged on during valid' end,
Case when loggoff_time < end_valid_period then 'Logged out early' else 'Logged off after valid' end
From #timekeeper
Where start_valid_period <= loggoff_time
And logon_time_id <= end_valid_period
Union All
Select username,
0,
'No overlap',
Case when logon_time_id > end_valid_period then 'Logon after valid' else '' end,
Case when loggoff_time < start_valid_period then 'Logged off before valid' else '' end
From #timekeeper
Where Not(
start_valid_period <= loggoff_time
And logon_time_id <= end_valid_period
)


Fred 10 Overlap Logged on early Logged out early
Wilma 10 Overlap Logged on during valid Logged off after valid
Barney 20 Overlap Logged on early Logged off after valid
Betty 5 Overlap Logged on during valid Logged out early
Pebbles 0 No overlap Logged off before valid
Bambam 0 No overlap Logon after valid

|||Thank you!!!

How can i check the time the Database is using?

My SQL 2000 server seems to be logging data an hour early, the Windows 2003
time is correct though. What steps should I take to find out what is
happening. I'm in the UK and we have to change our clocks for day light,
but these are all set to automatically adjust clocks.
Should it be using the local server time?I had a discussion with an Microsoft Consultant about this, from what I
remember. He said SQL server doesn't have time-zone setting it grabs it's
information from the Server its running on. So maybe check the settings on
the server ..
Ref Link: http://support.microsoft.com/?kbid=928388
--
Mohit K. Gupta
B.Sc. CS, Minor Japanese
MCTS: SQL Server 2005
"Gonzo" wrote:

> My SQL 2000 server seems to be logging data an hour early, the Windows 200
3
> time is correct though. What steps should I take to find out what is
> happening. I'm in the UK and we have to change our clocks for day light,
> but these are all set to automatically adjust clocks.
> Should it be using the local server time?
>|||SQL Server gets it date and time from the server itself thru an internal
winapi call. So if the server is correct then so is SQL Server. If you are
supplying the datetimes via the client as a value in the insert statement
then the client may be an hour behid. Can you post the actual code that is
doing the inserts?
Andrew J. Kelly SQL MVP
"Gonzo" <no@.no123.com> wrote in message
news:CF181373-2F00-4EE0-9B7F-6EAC76C705BE@.microsoft.com...
> My SQL 2000 server seems to be logging data an hour early, the Windows
> 2003 time is correct though. What steps should I take to find out what is
> happening. I'm in the UK and we have to change our clocks for day light,
> but these are all set to automatically adjust clocks.
> Should it be using the local server time?sql

How can i check the time the Database is using?

My SQL 2000 server seems to be logging data an hour early, the Windows 2003
time is correct though. What steps should I take to find out what is
happening. I'm in the UK and we have to change our clocks for day light,
but these are all set to automatically adjust clocks.
Should it be using the local server time?I had a discussion with an Microsoft Consultant about this, from what I
remember. He said SQL server doesn't have time-zone setting it grabs it's
information from the Server its running on. So maybe check the settings on
the server ..
Ref Link: http://support.microsoft.com/?kbid=928388
--
Mohit K. Gupta
B.Sc. CS, Minor Japanese
MCTS: SQL Server 2005
"Gonzo" wrote:
> My SQL 2000 server seems to be logging data an hour early, the Windows 2003
> time is correct though. What steps should I take to find out what is
> happening. I'm in the UK and we have to change our clocks for day light,
> but these are all set to automatically adjust clocks.
> Should it be using the local server time?
>|||SQL Server gets it date and time from the server itself thru an internal
winapi call. So if the server is correct then so is SQL Server. If you are
supplying the datetimes via the client as a value in the insert statement
then the client may be an hour behid. Can you post the actual code that is
doing the inserts?
--
Andrew J. Kelly SQL MVP
"Gonzo" <no@.no123.com> wrote in message
news:CF181373-2F00-4EE0-9B7F-6EAC76C705BE@.microsoft.com...
> My SQL 2000 server seems to be logging data an hour early, the Windows
> 2003 time is correct though. What steps should I take to find out what is
> happening. I'm in the UK and we have to change our clocks for day light,
> but these are all set to automatically adjust clocks.
> Should it be using the local server time?

How can I change the Subreport dynamically.

How can I change the Subreport dynamically. i.e at design time I have
mentioned a name for subreport but I need to change the subreport based on
one of the field value in my main report. How can I achive this'
--
vvOn Nov 19, 3:26 am, Xinxu <prajithpra...@.hotmail.com> wrote:
> How can I change the Subreport dynamically. i.e at design time I have
> mentioned a name for subreport but I need to change the subreport based on
> one of the field value in my main report. How can I achive this'
> --
> vv
You can either try using drill through instead of a subreport and use
an expression based on a field in the main report -or- create the
report programmatically based on some specific data, which would be
more work but allow for more flexibility. Hope this helps.
Regards,
Enrique Martinez
Sr. Software Consultant

How can I change the reports wizard templates?

I can easily create reports using the wizard, but I have to spend a lot of
time changing them.
Is there a way to change the templates the wizard uses?No. But you can create your own basic report as a template and change the
items needed by hand instead of using the wizard.
--
| From: "geri" <dsfds>
| Subject: How can I change the reports wizard templates?
| Date: Thu, 6 Jan 2005 12:21:10 +0200
| Lines: 5
| X-Priority: 3
| X-MSMail-Priority: Normal
| X-Newsreader: Microsoft Outlook Express 6.00.2800.1437
| X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2800.1441
| Message-ID: <OT9Urm98EHA.3828@.TK2MSFTNGP09.phx.gbl>
| Newsgroups: microsoft.public.sqlserver.reportingsvcs
| NNTP-Posting-Host: dbk-exc.dubek.co.il 62.219.254.181
| Path:
cpmsftngxa10.phx.gbl!TK2MSFTFEED02.phx.gbl!TK2MSFTNGP08.phx.gbl!TK2MSFTNGP09
.phx.gbl
| Xref: cpmsftngxa10.phx.gbl microsoft.public.sqlserver.reportingsvcs:38816
| X-Tomcat-NG: microsoft.public.sqlserver.reportingsvcs
|
| I can easily create reports using the wizard, but I have to spend a lot of
| time changing them.
| Is there a way to change the templates the wizard uses?
|
|
||||This is a multi-part message in MIME format.
--=_NextPart_000_002E_01C50EA5.CCFB9680
Content-Type: text/plain;
charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable
Then can you explain what the RS BOL topic "Creating a Report Using =Report Wizard" means by "Report Designer provides four style templates: =Bold, Casual, Corporate, and Compact. You can alter existing templates =or add new ones by editing the StyleTemplates.xml file in the =\80\Tools\Report Designer\Business Intelligence Wizards\Reports\Styles =folder in the Microsoft SQL Server program folder. This folder is =located on the computer on which Report Designer is installed. ", Please =? (Bold, italics, mine...)
""Brad Syputa - MS"" <bradsy@.Online.Microsoft.com> wrote in message =news:7BlC$jF9EHA.764@.cpmsftngxa10.phx.gbl...
> No. But you can create your own basic report as a template and change =the > items needed by hand instead of using the wizard.
> --
> | From: "geri" <dsfds>
> | Subject: How can I change the reports wizard templates?
> | Date: Thu, 6 Jan 2005 12:21:10 +0200
> | Lines: 5
> | X-Priority: 3
> | X-MSMail-Priority: Normal
> | X-Newsreader: Microsoft Outlook Express 6.00.2800.1437
> | X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2800.1441
> | Message-ID: <OT9Urm98EHA.3828@.TK2MSFTNGP09.phx.gbl>
> | Newsgroups: microsoft.public.sqlserver.reportingsvcs
> | NNTP-Posting-Host: dbk-exc.dubek.co.il 62.219.254.181
> | Path: > =cpmsftngxa10.phx.gbl!TK2MSFTFEED02.phx.gbl!TK2MSFTNGP08.phx.gbl!TK2MSFTNG=P09
> phx.gbl
> | Xref: cpmsftngxa10.phx.gbl =microsoft.public.sqlserver.reportingsvcs:38816
> | X-Tomcat-NG: microsoft.public.sqlserver.reportingsvcs
> | > | I can easily create reports using the wizard, but I have to spend a =lot of
> | time changing them.
> | Is there a way to change the templates the wizard uses?
> | > | > | >
--=_NextPart_000_002E_01C50EA5.CCFB9680
Content-Type: text/html;
charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
&

Then can you explain what the RS BOL =topic "Creating a Report Using Report Wizard" means by "Report Designer =provides four style templates: Bold, Casual, Corporate, and Compact. You =can alter existing templates or add new ones by editing the StyleTemplates.xml =file in the \80\Tools\Report Designer\Business Intelligence Wizards\Reports\Styles =folder in the Microsoft SQL Server program folder. This folder is =located on the computer on which Report Designer is installed. ", Please ? =(Bold, italics, mine...)
""Brad Syputa - MS"" wrote in message news:7BlC$jF9EHA.764@.cpmsftngxa10.phx.gbl...> =No. But you can create your own basic report as a template and change the > items =needed by hand instead of using the wizard.> =--> | From: "geri" > | Subject: How can I change the =reports wizard templates?> | Date: Thu, 6 Jan 2005 12:21:10 +0200> =| Lines: 5> | X-Priority: 3> | X-MSMail-Priority: =Normal> | X-Newsreader: Microsoft Outlook Express 6.00.2800.1437> | =X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2800.1441> | Message-ID: > | Newsgroups: microsoft.public.sqlserver.reportingsvcs> | NNTP-Posting-Host: dbk-exc.dubek.co.il 62.219.254.181> | Path: > cpmsftngxa10.phx.gbl!TK2MSFTFEED02.phx.gbl!TK2MSFTNGP08.phx.gbl!TK2MSFTNG=P09> phx.gbl> | Xref: cpmsftngxa10.phx.gbl microsoft.public.sqlserver.reportingsvcs:38816> | X-Tomcat-NG: microsoft.public.sqlserver.reportingsvcs> | > | I can =easily create reports using the wizard, but I have to spend a lot of> | =time changing them.> | Is there a way to change the templates the =wizard uses?> | > | > | >

--=_NextPart_000_002E_01C50EA5.CCFB9680--|||This is a multi-part message in MIME format.
--=_NextPart_000_0090_01C50EB7.5E3039B0
Content-Type: text/plain;
charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable
You CAN change the templates, but the BOL topic is deficient...
1.. CREATE A BACKUP of the StyleTemplates.xml file in the folder cited =in BOL (see post below).
2.. Open the file in a text editor (your favorite or XML editor...)
3.. Locate the "StyleTemplate" you want to change, e.g. "Compact"
4.. Make sure you understand what each element does. Refer to the BOL =Index for detailed info, e.g., "BorderWidth element" will give you blurb =on that element as used in rdl's AND the Template.
5.. Color values have NO spaces between words, e.g. Steel Blue is =coded SteelBlue.
6.. Font names CAN include spaces, e.g. <FontFamily>Arial =Black</FontFamily>
7.. DO NOT include a <TextAlign> pair in the "Table Header" Style - VS =barfs! (It seems to want to apply the alignment of the cell to the =corresponding table header cell - DUH!) A new post to be seen by MS =will hopefully get this recognized as a bug (if it hasn't already =been...).
8.. Despite setting a default font within the "Table" style, if you =expect it to be used when you add a Group, dream on...
9.. Save the edited XML file.
10.. NOW COPY THE SUCKER TO YOUR "LANGUAGE" FOLDER UNDER THE ..\Styles =FOLDER... e.g., for English, copy it to ..\Styles\EN\
11.. REBOOT (emotive term!) Visual Studio - it appears to cache the =Style file's XML the first time you use the "New Report Wizard".
Experiment with the Style File and you may be able to control things =like the page size, grid size, etc., but I've yet to pluck up that =degree of courage...
Hope this helps...
"SS_Newbie" <SS_Newbie@.community.nospam> wrote in message =news:uxuddjuDFHA.328@.tk2msftngp13.phx.gbl...
Then can you explain what the RS BOL topic "Creating a Report Using =Report Wizard" means by "Report Designer provides four style templates: =Bold, Casual, Corporate, and Compact. You can alter existing templates =or add new ones by editing the StyleTemplates.xml file in the =\80\Tools\Report Designer\Business Intelligence Wizards\Reports\Styles =folder in the Microsoft SQL Server program folder. This folder is =located on the computer on which Report Designer is installed. ", Please =? (Bold, italics, mine...)
""Brad Syputa - MS"" <bradsy@.Online.Microsoft.com> wrote in message =news:7BlC$jF9EHA.764@.cpmsftngxa10.phx.gbl...
> No. But you can create your own basic report as a template and =change the > items needed by hand instead of using the wizard.
> --
> | From: "geri" <dsfds>
> | Subject: How can I change the reports wizard templates?
> | Date: Thu, 6 Jan 2005 12:21:10 +0200
> | Lines: 5
> | X-Priority: 3
> | X-MSMail-Priority: Normal
> | X-Newsreader: Microsoft Outlook Express 6.00.2800.1437
> | X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2800.1441
> | Message-ID: <OT9Urm98EHA.3828@.TK2MSFTNGP09.phx.gbl>
> | Newsgroups: microsoft.public.sqlserver.reportingsvcs
> | NNTP-Posting-Host: dbk-exc.dubek.co.il 62.219.254.181
> | Path: > =cpmsftngxa10.phx.gbl!TK2MSFTFEED02.phx.gbl!TK2MSFTNGP08.phx.gbl!TK2MSFTNG=P09
> phx.gbl
> | Xref: cpmsftngxa10.phx.gbl =microsoft.public.sqlserver.reportingsvcs:38816
> | X-Tomcat-NG: microsoft.public.sqlserver.reportingsvcs
> | > | I can easily create reports using the wizard, but I have to spend =a lot of
> | time changing them.
> | Is there a way to change the templates the wizard uses?
> | > | > | >
--=_NextPart_000_0090_01C50EB7.5E3039B0
Content-Type: text/html;
charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
&

You CAN change the templates, but the =BOL topic is deficient...
CREATE A BACKUP of the =StyleTemplates.xml file in the folder cited in BOL (see post below).
Open the file in a text editor (your =favorite or XML editor...)
Locate the "StyleTemplate" you =want to change, e.g. "Compact"
Make sure you understand what each =element does. Refer to the BOL Index for detailed info, e.g., "BorderWidth element" =will give you blurb on that element as used in rdl's AND the =Template.
Color values have NO spaces between =words, e.g. Steel Blue is coded SteelBlue.
Font names CAN include spaces, e.g. Arial Black
DO NOT include a =pair in the "Table Header" Style - VS barfs! (It seems to want to apply the =alignment of the cell to the corresponding table header cell - DUH!) A =new post to be seen by MS will hopefully get this recognized as a bug (if it =hasn't already been...).
Despite setting a default font within =the "Table" style, if you expect it to be used when you add a Group, dream on...
Save the edited XML file.
NOW COPY THE SUCKER TO YOUR "LANGUAGE" =FOLDER UNDER THE ..\Styles FOLDER... e.g., for English, copy it to ..\Styles\EN\
REBOOT (emotive term!) Visual Studio - =it appears to cache the Style file's XML the first time you use the "New =Report Wizard".
Experiment with the Style File and you =may be able to control things like the page size, grid size, etc., but I've yet to =pluck up that degree of courage...
Hope this helps...
"SS_Newbie" wrote in message news:uxuddjuDFHA.328@.t=k2msftngp13.phx.gbl...
Then can you explain what the RS BOL =topic "Creating a Report Using Report Wizard" means by "Report Designer =provides four style templates: Bold, Casual, Corporate, and Compact. =You can alter existing templates or add new ones by editing the =StyleTemplates.xml file in the \80\Tools\Report Designer\Business Intelligence Wizards\Reports\Styles folder in the Microsoft SQL Server program folder. This folder is located on the computer on which =Report Designer is installed. ", Please ? (Bold, italics, mine...)

""Brad Syputa - MS"" wrote in message news:7BlC$jF9EHA.764@.cpmsftngxa10.phx.gbl...> No. But you =can create your own basic report as a template and change the > items =needed by hand instead of using the wizard.> --> =| From: "geri" > | Subject: How can I change the reports =wizard templates?> | Date: Thu, 6 Jan 2005 12:21:10 +0200> | =Lines: 5> | X-Priority: 3> | X-MSMail-Priority: Normal> =| X-Newsreader: Microsoft Outlook Express 6.00.2800.1437> | =X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2800.1441> | Message-ID: > | Newsgroups: microsoft.public.sqlserver.reportingsvcs> | NNTP-Posting-Host: dbk-exc.dubek.co.il 62.219.254.181> | Path: > =cpmsftngxa10.phx.gbl!TK2MSFTFEED02.phx.gbl!TK2MSFTNGP08.phx.gbl!TK2MSFTNG=P09> phx.gbl> | Xref: cpmsftngxa10.phx.gbl microsoft.public.sqlserver.reportingsvcs:38816> | X-Tomcat-NG: microsoft.public.sqlserver.reportingsvcs> | > | I can =easily create reports using the wizard, but I have to spend a lot of> =| time changing them.> | Is there a way to change the templates the =wizard uses?> | > | > | >

--=_NextPart_000_0090_01C50EB7.5E3039B0--

How can I change the default Save-As/Save directory

I am new to sql sever management studio express, but a long time query analyzer user. This is a very basic question.

I want to change the default directory in sql server management studio express so that when I go to save a query, it is already pointed to the correct one. Where do I change that?

Thanks,

Nanci

Goto [Tools], [Options], [Query Results]

There you will be able to change the default query results storage location.

|||

I have changed that setting, but it only works for the results of the query, not saving the query itself. Any other suggestions?

Nanci

sql

Monday, March 26, 2012

How can I change the default identity_range value in Merge replication

I have set up Merge Replication and everything is fine until a subscriber
goes offline for any length of time. The issue has to do with the setting of
the @.identity_range parameter for each article.
I am configuring the publication through the SQL Management Studio (server
is SQL 2005) and realise that I can run scripts and even alter the values
through the IDE.
What I want to do is change the default value that the IDE uses when it adds
the articles. The default seems to be 1000 which isn't really enough. We
would like to change the default to something like 10000
Does anybody know where SQL 2005 would store this value?
Thanks in advance,
Andrew Stanford
It is best that you not change meta data values in system tables. I'll
provide a way to change the indentiy range value for subscribers via the UI.
Since you already defined a merge publication, access the publication
properties by right clicking on the publication name under the
Replication:Local Publications node in SQL 2005 Management Studio. In the
left pane, select Articles. In the right pane, select the article you would
like to change the identity range values for. After highlighting the
article, use the Article Properties button. Scroll down to the identity
range management section and you should be able to change the Subscriber
Range Size value from 1000 to 10000. Hit OK, OK to confirm the changes.
Note that since you have an active merge publication already defined, the
subscriber will continue to use the old identity range values until they are
exhausted. The next time the merge agent requests a new ientitiy range from
the publisher, it will start using the new subscriber range value of 10000.
If you were to create a new publication, when you define the articles that
are in the publication you are able to drill into article properties and set
the subscriber range value to something other than 1000 up front.
Hope this helps,
Tom
This posting is provided "AS IS" with no warranties, and confers no rights.
"Andrew Stanford" <andrew.stanford@.bakertilly.co.uk> wrote in message
news:uUeZt4j2FHA.956@.TK2MSFTNGP10.phx.gbl...
>I have set up Merge Replication and everything is fine until a subscriber
>goes offline for any length of time. The issue has to do with the setting
>of the @.identity_range parameter for each article.
> I am configuring the publication through the SQL Management Studio (server
> is SQL 2005) and realise that I can run scripts and even alter the values
> through the IDE.
> What I want to do is change the default value that the IDE uses when it
> adds the articles. The default seems to be 1000 which isn't really enough.
> We would like to change the default to something like 10000
> Does anybody know where SQL 2005 would store this value?
>
> Thanks in advance,
> Andrew Stanford
>

How can i change the chart type at runtime?

Hi friends,

I want to display my report with different chart.

The type of chart to be display will be choosen only on exection time.

Can any one help me by giving solution to my problem?

Thank you

Currently, SSRS doesn't support changing the report definition at runtime. To implement your requirement consider an application front end to change and deploy the report definition. If this is not an option, the other option is to have all supported chart types on the report and hide conditionally the ones you don't need. The later approach may have performance ramifications.

How can I catch all errors of the stored at the same time?

I have a stored prcedure . In the stored I wrote 3 SQL statements, one is OK but 2 other statements have error as:

1. Invalid column name 'F2'

2. Invalid object name '##_152008049'.

I put the stored inside try block and catch error in catch block as the following. But I always catch only the first error : invalid column name F2 . How about the second statement?

How can I catch all the errors when I put the stored in try block. Now I don't want to add try..catch inside the store for each statement.

Begin try

exec mystored

End try

begin catch

ERROR_NUMBER() AS ErrorNumber,

ERROR_SEVERITY() AS ErrorSeverity,

ERROR_STATE() as ErrorState,

ERROR_PROCEDURE() as ErrorProcedure,

ERROR_LINE() as ErrorLine,

ERROR_MESSAGE() as ErrorMessage,

end catch

You are only getting the first one, because when you encounter the first error, it will fall through to the catch block. Any statements after the error don't even get executed.|||Not all errors are of the same kind, there is a difference between statement abort and batch abort errors. But as the previous poster already said, there is no way to return to the next statement after the catch block was handled.

HTH, Jens Suessmeyer.

http://www.sqlserver2005.de

Friday, March 23, 2012

How can I be convinced by what the model says in particular for Time series?

Hi, all here,

I want to hear from you for your experiences on how can we be convinced by what the model predicts particularly for Time Series algorithm? As we are not able to see the model accuracy chart for that, in this case, how can use the model results? E.g. we wanna know the possible sales amount of next month for a particular store in order to buy in the goods, in this case, how can we make the most of the prediction by the model? To shop ower, well, if the result is too far away from the usual sales amount, then it is unbelievable, thus, in this case, what else can we try? Keep training the models until its results sounds reasonable? Or what else can we try?Thanks in advance for your advices and help and I am looking forward to hearing from you shortly.

With best regards,

Yours sincerely,

Manually, you could train your model with only some part of your data (say, without the last month) and see how the predictions compare with the actual values for the last month.

The algorithm allows you to specify a parameter, HISTORIC_MODEL_COUNT.
In the series viewer, you can choose to display historic predictions and compare them with the real data

This should give you an idea of how good the predictions are. Also, in the series viewer, you can choose to display the error associated with the forecast values, which should give an idea about the confidence of the prediction|||

Hi, Bogdan,

Thanks a lot for your very kind advices and help.

With best regards,

Yours sincerely,

How can I be convinced by what the model says in particular for Time series?

Hi, all here,

I want to hear from you for your experiences on how can we be convinced by what the model predicts particularly for Time Series algorithm? As we are not able to see the model accuracy chart for that, in this case, how can use the model results? E.g. we wanna know the possible sales amount of next month for a particular store in order to buy in the goods, in this case, how can we make the most of the prediction by the model? To shop ower, well, if the result is too far away from the usual sales amount, then it is unbelievable, thus, in this case, what else can we try? Keep training the models until its results sounds reasonable? Or what else can we try?Thanks in advance for your advices and help and I am looking forward to hearing from you shortly.

With best regards,

Yours sincerely,

Manually, you could train your model with only some part of your data (say, without the last month) and see how the predictions compare with the actual values for the last month.

The algorithm allows you to specify a parameter, HISTORIC_MODEL_COUNT.
In the series viewer, you can choose to display historic predictions and compare them with the real data

This should give you an idea of how good the predictions are. Also, in the series viewer, you can choose to display the error associated with the forecast values, which should give an idea about the confidence of the prediction|||

Hi, Bogdan,

Thanks a lot for your very kind advices and help.

With best regards,

Yours sincerely,

sql

How can I be assured that I do have SP1 applied correctly in SQL 2005 Developer Edition

I installed my SQL 2005 Developer edition and applied the SP1. I didn’t have a time to wait the installation to complete (I needed to reboot) so I cancelled the SP1 which was downloaded from Windows Update.

Now, my development PC says that SQL 2005 SP1 is applied but I am not sure if it’s applied correctly. I tried to reinstall SP1 in order to be assured but I can’t get it reinstalled. I get error message saying that you already have SP1 2047 ENU applied.

I just don’t want (have a time) to troubleshoot some possible upcoming issues in development because of this. So, how can I be assured that I do have SP1 applied correctly?

At what stage you have to rebooted the box?

if this is used for a testing on production, then its better to resintall afresh to avoid any spurious errors in future.

Run SELECT @.@.VERSION and see the results.

|||

Yes. 9.00.2047 is the SQL Server 2005 SP1 version. You can verify the following items to get more confidence.

1. Add/Remove Program in control panel to check the status of SQL Server 2005.

2. Go to registry keys HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL.1\Setup to check the version.

3. You can check the file version of %ProgramFiles%Microsoft SQL Server\MSSQL.<instance id>\MSSQL\Binn\sqlservr.exe.

|||

I try to uninstall the SP1 but its not possible, so I guess in order to be safe I should uninstall the SQL 2005 developer edition completely and reinstall it and apply the batch again.

It looks all good in SQL site, but SQL reported the SP1 applied and Microsoft Update reported the SP1 cancelled. This is a bit wired, so I going to do the reinstallation in order avoid any spurious errors in future.

Thanks folks....You great....

Alexander

How can I automate the column titled as ID NUmber in my database, in VS 2005?

I have a table with a primary key titled as 'ID NUmber' which needs to be created automatically, however every time i add a new record the ID is not added and i have to write it manually i.e. 1, 2, 3.., could you please advice me how i can format this; i know you can do this with microsoft Access but with VS 2005 + VB language this option is not available under data type

*i am using VS 2005 and VB language

Go into design view for the table

toward the bottom, you'll see Identity Specification - open that up and set IS IDentity to True

|||Thank you, i have found the 'IS identity' but mine is set to 'No' and is blocked (i can't click on it). should i be using an specific data type; currenly i am using 'Real' is that right? I had to use 'Real' as with other data types the option for 'primary key' was not available.|||

Generally (though it might be possible some other way that I'm not familiar with), the way to do this is with an INT datatype, so it can automatically increment.

Maybe someone else can chime in here, how to do it some other way

|||

To set a column as an Identity column the datatype has to be one of the INT types - tinyint, smallint, int, bigint etc.

|||

i have used the tinyint to set the IS identity as 'yes', however when i run the database and add a new row to the database the row id is for example 9 instead of 2, even though i have deleted all the previous records and doesn't realise that i have now only 1 row and that the next id should be 2. is there any way to correct this?

|||

You need to read up books online about Identity columns. Once a number is assigned to a row, its gone. Even if the row is deleted the number is gone. Any new rows will get the next number. If you were doing this as a test and want to empty the table and reset the identity you can TRUNCATE the table instead of delete. Again, before doing the truncate, read up books online about the command. You can also use DBCC CHEKCIDENT to reset the seed value.

|||Remember, also - tinyint is defined like this:

tinyint

0 to 255

So - I'd recommend at least using INT

One last thing also - you said that your column is titled "ID Number"

My (and others) recommend that you remove the space (IDNumber) and that you never put spaces in your field or table names. Believe me, this will cause you less grief in the future.

Wednesday, March 21, 2012

how can I add a time stamp on a table

How can I know when a record on a table has been modified ?
I want to add a field and fill it with a date/time when the recors is modified
ThanksThe only way I know is to use a trigger (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/tsqlref/ts_create2_7eeq.asp) to update the column.

-PatP|||Take a look at Lumigent Log Explorer. It allows you to peep into transaction logs to find out who did what when.|||Date and Time Functions
These scalar functions perform an operation on a date and time input value and return a string, numeric, or date and time value.

This table lists the date and time functions and their determinism property. For more information about function determinism, see Deterministic and Nondeterministic Functions.

Function Determinism
DATEADD Deterministic
DATEDIFF Deterministic
DATENAME Nondeterministic
DATEPART Deterministic except when used as DATEPART (dw, date). dw, the weekday datepart, depends on the value set by SET DATEFIRST, which sets the first day of the week.
DAY Deterministic
GETDATE Nondeterministic
GETUTCDATE Nondeterministic
MONTH Deterministic
YEAR Deterministic

See Also

Functions

1988-2000 Microsoft Corporation. All Rights Reserved.|||USE Northwind
GO

CREATE TABLE myTable99(
Col1 int IDENTITY(1,1) NOT NULL PRIMARY KEY
, Col2 char(1)
, ADD_TS datetime DEFAULT GetDate()
, ADD_BY varchar(255) DEFAULT System_User)
GO

-- OK We don't know who did what when, except when it was added

INSERT INTO myTable99(Col2)
SELECT 'A'

SELECT * FROM myTable99

UPDATE myTable99
SET Col2 = 'B'
WHERE Col1 = 1

SELECT * FROM myTable99
OK

-- OK Lets see what we can do
-- Alter the table to track the updates

ALTER TABLE myTable99 ADD UPDATE_TS datetime
GO

ALTER TABLE myTable99 ADD UPDATE_BY varchar(255)
GO

-- Set up a trigger to do the work

CREATE TRIGGER myTrigger99 ON myTable99
FOR UPDATE
AS
BEGIN
UPDATE m
SET UPDATE_BY = System_User
, UPDATE_TS = GetDate()
FROM myTable99 m
INNER JOIN inserted i
ON i.Col1 = m.Col1
END
GO

-- viola

INSERT INTO myTable99(Col2)
SELECT 'C'

SELECT * FROM myTable99

UPDATE myTable99
SET Col2 = 'D'
WHERE Col1 = 2
SELECT * FROM myTable99
OK

DROP TRIGGER myTrigger99
DROP TABLE myTable99
GO|||If you don't like triggers, then you could re-write the application to use only stored procedures to update the tables, then remove update permissions from the tables, to make sure no one sneaks in the back way.|||And if you don't care about getting an actual Date/Time value from the field (just uniqueness), then you can use the timestamp datatype. It's a binary value that is unique in the database, but does not actually represent a date or a time. The benefit is that it automatically updates when the row is updated without the need for any additional code.|||And if you don't care about getting an actual Date/Time value from the field (just uniqueness), then you can use the timestamp datatype. It's a binary value that is unique in the database, but does not actually represent a date or a time. The benefit is that it automatically updates when the row is updated without the need for any additional code.

Huh?

And as for using a sproc...it's no guarentee...

No reason not to use a trigger like this...

Anyone?|||SQL Server Books Online

timestamp is a data type that exposes automatically generated binary numbers, which are guaranteed to be unique within a database. timestamp is used typically as a mechanism for version-stamping table rows. The storage size is 8 bytes.
...
A table can have only one timestamp column. The value in the timestamp column is updated every time a row containing a timestamp column is inserted or updated...
...
A nonnullable timestamp column is semantically equivalent to a binary(8) column. A nullable timestamp column is semantically equivalent to a varbinary(8) column.

I'm just saying, if he's looking for a field that will automatically update without having to do any coding, a timestamp field will do that.

He never said he needed to know the date/time the record was updated, he said he wanted to know when a record is modified. You'd know the record has been modified when the timestamp field changes.|||Going with the stored procedure requires that the DBAs ensure that the programmers don't try to back-end him/her. This would take a (politically) strong DBA group, that can enforce such a rule. Or being able to revoke that all important update permission, which forces the application to use the stored procedure.|||Stored procedures are not sufficient to guarantee relational or data integrity. Somebody can and will eventually hook directly into the table and bypass your logic.

Yeah, the timestamp updates. But how do you KNOW it updated unless you retain the previous value?

The thing you have to worry about is when a record thinks it has been updated, but actually the new data is the same as the previous data. If you have a value in your database such as gender that is "Male" and run:

Update mytable set gender = 'Male'

... the update trigger will run even though the data has not changed. In cases where this distinction is important, I've solved the problem by running a binarychecksum comparison between the new record and the old record.|||Right. But we don't know how he's using the date/time field, so any specific recommendation is moot without additional details on his requirements.|||... Somebody can and will eventually hook directly into the table and bypass your logic...?
Can you give us an example on how you'd go about doing it?
:rolleyes:|||Doing what?

Hooking into the table?
update table set thecolumn = somebaddatavalue

Implementing better integrity?
Use a trigger.

Checking to see whether the data had changed?
Use something like where binarychecksum(inserted.*) <> binarychecksum(currentdata.*), but I'd have to look up my old code to see exactly what syntax I used. I seem to recall using having to use subqueries to get around some of the limitations of the binarychecksum input parameters.

If nanou9999 is interested, I look it up when I have time.|||That's why I keep saying you have to be able to remove the permission to update the table.|||That's why I keep saying you have to be able to remove the permission to update the table.EXACTLY!!!

So my question to blindman was how he'd go about "hooking" (what a term!) into a table, if ALL permissions are denied, and the only way to affect the data is through stored procedures.

I guess I need to be more elaborate in stating my questions, huh?! ;)

So, blindman, how would you "hook" into a table (...hmmmmm...your update will fail, you know)?|||Perhaps you trust your Database Administrators never to directly change data in a table, but I do not. Or perhaps I just build my database applications to be more robust than you do.

If a rule applies to the data, then implement it at the data level, not in every procedure that accesses the data. Common sense.

Now go ahead with your next inane, hair-splitting post, because I know you must, but I'm done with this thread. Ta-ta... :cool:|||... Or perhaps I just build my database applications to be more robust than you do.
I doubt it, but...Is this a challenge?
...If a rule applies to the data, then implement it at the data level, not in every procedure that accesses the data. Common sense. That's a front-end coder's answer, not an application architect's one, but then I never suspected you to be of that caliber either ;)
...Now go ahead with your next inane, hair-splitting post, because I know you must, but I'm done with this thread. Ta-ta...
And as you see I do, but only to demonstrate that you are not the one to decide whether the thread should be closed or not. BTW, the rest of us don't think of ourselves that high-up-in-the-sky either ;) Get off of your cloud of self-praising and adoration of your superiority, be simpler, and people will love you :p|||EDIT: Nevermind...sql

Monday, March 19, 2012

How can db_owner restore db from backup and keep his permissions?

Hi there
I'm developing an application, and from time to time I take it to
production environment and keep it up to date with dev version. When I
tried to do this alone (istead of sysadmin) I got some error saying
that I didn't have enough permissions to do restore (despite I was a
db_owner).
Is it possible, that the reason for that is the fact that in dev
version which I was restoring there was no user which had db_owner
permissions? so, I was working on this database as some user with
db_owner permissions and restored it to the state in which there wasn't
any user mapped to my login in db anymore.
Is it possible? If so, then how can I restore db as a db_owner?
thanks a lot
HPFrom BOL:
"If the database being restored does not exist, the user must have CREATE
DATABASE permissions to be able to execute RESTORE. If the database exists,
RESTORE permissions default to members of the sysadmin and dbcreator fixed
server roles and the owner (dbo) of the database (for the FROM
DATABASE_SNAPSHOT option, the database always exists)."
Cheers,
Paul Ibison SQL Server MVP, www.replicationanswers.com .

How can db_owner restore db from backup and keep his permissions?

Hi there
I'm developing an application, and from time to time I take it to
production environment and keep it up to date with dev version. When I
tried to do this alone (istead of sysadmin) I got some error saying
that I didn't have enough permissions to do restore (despite I was a
db_owner).
Is it possible, that the reason for that is the fact that in dev
version which I was restoring there was no user which had db_owner
permissions? so, I was working on this database as some user with
db_owner permissions and restored it to the state in which there wasn't
any user mapped to my login in db anymore.
Is it possible? If so, then how can I restore db as a db_owner?
thanks a lot
HP
From BOL:
"If the database being restored does not exist, the user must have CREATE
DATABASE permissions to be able to execute RESTORE. If the database exists,
RESTORE permissions default to members of the sysadmin and dbcreator fixed
server roles and the owner (dbo) of the database (for the FROM
DATABASE_SNAPSHOT option, the database always exists)."
Cheers,
Paul Ibison SQL Server MVP, www.replicationanswers.com .

How can db_owner restore db from backup and keep his permissions?

Hi there
I'm developing an application, and from time to time I take it to
production environment and keep it up to date with dev version. When I
tried to do this alone (istead of sysadmin) I got some error saying
that I didn't have enough permissions to do restore (despite I was a
db_owner).
Is it possible, that the reason for that is the fact that in dev
version which I was restoring there was no user which had db_owner
permissions? so, I was working on this database as some user with
db_owner permissions and restored it to the state in which there wasn't
any user mapped to my login in db anymore.
Is it possible? If so, then how can I restore db as a db_owner?
thanks a lot
HPFrom BOL:
"If the database being restored does not exist, the user must have CREATE
DATABASE permissions to be able to execute RESTORE. If the database exists,
RESTORE permissions default to members of the sysadmin and dbcreator fixed
server roles and the owner (dbo) of the database (for the FROM
DATABASE_SNAPSHOT option, the database always exists)."
Cheers,
Paul Ibison SQL Server MVP, www.replicationanswers.com .

how can check the time?

I have a stored procedure and I want to run a command based on time so if the time is after 8pm the charge the client US$ 10 otherwise US$ 8

Code Snippet


charge = case when datepart(hour, getdate())>=20 then 10 else 8 end

|||

That covers it up to midnight. Most likely you will also want to continue past midnight up to some early morning time.

If so, then something like this: (building on phdiwakar's suggestion) to charge $10 between 8 PM and 6 AM


Code Snippet

Charge = CASE
WHEN ( datepart( hour, getdate()) >= 20
OR datepart( hour, getdate()) <= 5
) THEN 10
ELSE 8
END

Friday, March 9, 2012

How are views used each time it is requested.

Taking the view below, is a view reran each time it is requested or is there
some sort of caching that would hold the dataset ready for the next request
of the view?
CREATE VIEW dbo.vwTodaysNeurologyAppts
AS
SELECT TOP 100 PERCENT PatientName, ResourceCode, ApptDate, ActivityType
FROM dbo.Appointment
WHERE (LEFT(ResourceGroup, 3) = 'NEU') AND (DATEDIFF(Day, ApptDate,
GETDATE()) = 0) AND (ApptStatus = 'ATTENDED')
ORDER BY ApptDateNo caching of the dataset, as that would be incredibly complex considering t
hat the underlying data
might have been modified in between. The data that has been accessed by the
query you ran against
the view can of course be cached (just as if you were querying those tables
directly).
You can create an index on a view (under certain circumstances) which essent
ially materializes the
view. Any modification if the underlying data need to be propagated to the m
aterialized/indexed
view.
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
Blog: http://solidqualitylearning.com/blogs/tibor/
"CD" <mcdye1@.hotmail.REMOVETHIS.com> wrote in message
news:OfR%23iKDKGHA.2992@.tk2msftngp13.phx.gbl...
> Taking the view below, is a view reran each time it is requested or is the
re some sort of caching
> that would hold the dataset ready for the next request of the view?
>
> CREATE VIEW dbo.vwTodaysNeurologyAppts
> AS
> SELECT TOP 100 PERCENT PatientName, ResourceCode, ApptDate, ActivityTy
pe
> FROM dbo.Appointment
> WHERE (LEFT(ResourceGroup, 3) = 'NEU') AND (DATEDIFF(Day, ApptDate, GE
TDATE()) = 0) AND
> (ApptStatus = 'ATTENDED')
> ORDER BY ApptDate
>|||no, the results are not cached between executions - but the source data
pages are, and depending on the level of activity on the server, there is a
good chance that they will still be in memory on successive executions.
however, you can persist the view by creating a clustered index on it - see
"indexed views" in BOL.
btw, don't rely on "SELECT TOP 100 PERCENT" and "ORDER BY" inside a view.
ORDER BY should be specified in the final SELECT. also, if there is an index
on ApptDate column, don't use DATEDIFF on it because the index won't be
used.
dean
"CD" <mcdye1@.hotmail.REMOVETHIS.com> wrote in message
news:OfR%23iKDKGHA.2992@.tk2msftngp13.phx.gbl...
> Taking the view below, is a view reran each time it is requested or is
> there some sort of caching that would hold the dataset ready for the next
> request of the view?
>
> CREATE VIEW dbo.vwTodaysNeurologyAppts
> AS
> SELECT TOP 100 PERCENT PatientName, ResourceCode, ApptDate,
> ActivityType
> FROM dbo.Appointment
> WHERE (LEFT(ResourceGroup, 3) = 'NEU') AND (DATEDIFF(Day, ApptDate,
> GETDATE()) = 0) AND (ApptStatus = 'ATTENDED')
> ORDER BY ApptDate
>|||Each SELECT statement performed against the view will result in a SELECT
statement against the base tables. Data is cached in memory to make
subsequent SELECTS against the view faster, but the actual view data is
stored only in the base tables unless you create a clustered index on the
view. Indexes with views, also known as materialized views, have a seperate
data store for the columns in the view within the clustered index.
If you wanted to index your view, you would have to remove the TOP clause,
which would also necessitate removing the ORDER BY clause.
"CD" wrote:

> Taking the view below, is a view reran each time it is requested or is the
re
> some sort of caching that would hold the dataset ready for the next reques
t
> of the view?
>
> CREATE VIEW dbo.vwTodaysNeurologyAppts
> AS
> SELECT TOP 100 PERCENT PatientName, ResourceCode, ApptDate, ActivityTy
pe
> FROM dbo.Appointment
> WHERE (LEFT(ResourceGroup, 3) = 'NEU') AND (DATEDIFF(Day, ApptDate,
> GETDATE()) = 0) AND (ApptStatus = 'ATTENDED')
> ORDER BY ApptDate
>
>

How are Execution Paths built?

Lets say you create a view.

then you select from that view for the first time. with no where clause.

Does it build a different execution path than it does if you select from that view with a where clause?

Hi,

Dynamic SQL statements are parameterized if possible (simple where ID = 5 might be cached as ID = ?) or the exact query text is used as a reference. So querying against your view with different criteria will generate different query plans.

WesleyB

Visit my SQL Server weblog @. http://dis4ea.blogspot.com

|||Think of a view as basically a "macro" which inserts the view's select statement into your code at execution time. The execution plan is created when you use the view.

So, yes, the execution plan is different based on your where clause.

|||so would you say its better to have your first query against a view not have a where clause?
|||No. There is no reason to run a query on a view with no where clause. The execution plan is recreated every time the view is used.

|||I am not saying you are incorrect and i do appreciate your comments, but the first time i use a view it takes a little longer than all the other times i use the view. I understand this to be because it is building the Execution path and optimizing the views Execution path.|||

Yes, it would be slower the first time because of creating the execution plan. And it will use the same execution plan for similar where statements.

But, running a view with no where does nothing, unless you do that over and over. If you put in a "WHERE field=x" it creates an execution plan based on that. Then if you do "WHERE field2=y" it makes a new exeuction plan. It MIGHT have the plan cached if you have used a similar plan before, but you can't count on it.

|||

Thank you sir,

That answer helps me unserstand immensely. so it builds a different Execution path per each unquely patterened where clause..