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

Tuesday, March 27, 2012

Configuration Manager ?

Each time you start a SSIS project you have Solutions Configuration showing "Development". In the drop down box you can select "Configuration Manager..."

Can someone tell me the use of this, and is it related to the package configurations somehow. I've tried to create new Solution Configurations like "Test" and "Production" with the purpose of binding different configuration files and deplymentfolders to each Solution Configuration but still it seems like this isn't the way i should be used...

This is something inherent to Visual Studio rather than BIDS or SSIS. It doesn't have any relevance to package configurations that we know and love (!!!).

I don't know how this VS feature is supposed to be used so I say whether it would be useful for SSIS or not. I'd like to know though!!!

-Jamie

|||

The only thing i could see any use of this was to create 3 enviroments - Development, Test and Production.

I each of those i'll set the outputpath to bin\Development, bin\Test, bin\Production

So when i build the package i can choose the enviroment to build it to so that i can keep those files sepperate....

|||

Is there a way to reference the current value within a variable ?

This would be helpfull for having the servername depend on the selected configuration.

Thanks in advance,

Geert

|||

What you are asking and what cpgl described seems totally unnecessary if you only use the built in Configuration support for SSIS. Things like file paths are server names should be changed through configurations, not coded into the package during "build".

I would expect each environment to have the required configiration resources in place, so there should be nothing to change in the package to prepare it for an environment. If you do change the package between environments it just defeats the purpose of having a test environment as what you tested is not what you will then promote to production. It may be a minor change, but being strict, no changes should be allowed.

The only exception I can see is when environments are combined on machines, and for that I'd recomend passing in a parameter through the execution host, e.g. DTEXEC /SET

Tuesday, March 20, 2012

conditionally executing sql statement

I need to write .sql file in a dynamic way.
inside the file i need to decide at run time (of the sql script) whether or
not to run a SQL statement that I don't know it's content while dynamically
creating the sql script, this sql statement might include a GO statement
what makes a problem putting it inside an if begin end block.
for example
in my script a runtime check
select @.runStatement = configVal from database at script runtime execution
if @.runStatement =1
begin
-- here comes an unknown sql statement at the time of creating the sql
script that might include a GO command which will break the syntax of the
entire block
-- go <- this here makes a TSQL error for the end command since it
breaks the begin / end block.
end
can someone recomend of an approach for how to solve this?
execute sql is not an option here since the internal SQL statement might be
larget then 4000 nvarchar characters and I can not declarae a @.ntext local
variable
TIA.>> inside the file i need to decide at run time (of the sql script) whether
Under normal circumstances, this is a poor way to write SQL code. The kludgy
workaround is to assign the SQL statement to a variable, replace the tokens
that are not needed and use EXEC or sp_ExecuteSQL to execute it.
The right way can be suggested only if you can explain the overall
situation. Why do you have to resort to such complex approach? Is there a
3rd party tool involved?
Anith|||martin (news.microsoft.com) writes:
> I need to write .sql file in a dynamic way.
> inside the file i need to decide at run time (of the sql script) whether
> or not to run a SQL statement that I don't know it's content while
> dynamically creating the sql script, this sql statement might include a
> GO statement what makes a problem putting it inside an if begin end
> block.
> for example
> in my script a runtime check
> select @.runStatement = configVal from database at script runtime execution
> if @.runStatement =1
> begin
> -- here comes an unknown sql statement at the time of creating the
> sql script that might include a GO command which will break the syntax
> of the entire block
> -- go <- this here makes a TSQL error for the end command since it
> breaks the begin / end block.
> end
>
> can someone recomend of an approach for how to solve this?
> execute sql is not an option here since the internal SQL statement might
> be larget then 4000 nvarchar characters and I can not declarae a @.ntext
> local variable
Are you on SQL 2000 or SQL 2005?
If you are on SQL 2000, I would srtongly recommend that you run the
control loop from a client. It could be very difficult to sort out
from SQL only. It could be a little easier on SQL 2005, since there
you can work with nvarchar(MAX) and you could do the batch splitting
in CLR code.
I echoes Aniths suggestion that you could be better served by telling
us the full story. This could give you better suggestions.
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx|||it should support database modifications / upgrades.
the commands are not known at the time of designing the tool that will
execute the statements.
i understand that running each script from a client tool like a VB.NET app
is a good option but is it not possible to run it from sql script file using
some goto label....?
"Anith Sen" <anith@.bizdatasolutions.com> wrote in message
news:eedlU0VaGHA.1020@.TK2MSFTNGP02.phx.gbl...
> Under normal circumstances, this is a poor way to write SQL code. The
> kludgy workaround is to assign the SQL statement to a variable, replace
> the tokens that are not needed and use EXEC or sp_ExecuteSQL to execute
> it.
>
> The right way can be suggested only if you can explain the overall
> situation. Why do you have to resort to such complex approach? Is there a
> 3rd party tool involved?
> --
> Anith
>|||martin (news.microsoft.com) writes:
> it should support database modifications / upgrades.
> the commands are not known at the time of designing the tool that will
> execute the statements.
> i understand that running each script from a client tool like a VB.NET
> app is a good option but is it not possible to run it from sql script
> file using some goto label....?
Possible and possible. With severe kludges maybe. And it depends on the SQL
Server version.
If the purpose of the tool is run scripts for database changes, I strongly
recommend using a control part in a client language.
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspxsqlsql

Conditional Where Clause w/ Case Statement Possible?

Greetings,

After many hours search many forums and many failed experiments, I figure it's time to turn to the experts.

I need to execute a query that changes the returned data based upon a parameter's value. In my example below, the lob field contains both text values and nulls.

SELECT uniqueID, lob, xdate

FROM mytable

WHERE

CASE WHEN @.myparam = 'ALL'

THEN

xdate >= '2007-09-01'

ELSE

xdate >= '2007-09-01' or

lob = @.myparm

END

I've experimented with various forms of the LIKE function, checking for null/not null and keep coming up blank.

I thought about using an IF statement and creating different versions of the entire statement, however, in real-life I need to do this with four fields using four parameters (one for each field). The permutations are a little too much.

Any ideas?

Rob

Your query can be written this way, I think:

SELECT uniqueID, lob, xdate

FROM mytable

WHERE (xdate >= '20070901')

AND (

@.myparm = 'ALL'

OR

lob = @.myparm

)

In general, you can probably write:

WHERE

(@.p = 'Option1' AND (<option 1 condition>))

OR

(@.p = 'Option 2' AND (<option 2 condition>))

OR

...

Be careful where parentheses go, so AND and OR don't associate differently than you want.

In SQL, CASE .. END is an expression, by the way, so it can't be used as you hoped in your post.

Steve Kass

Drew University

http://www.stevekass.com

|||

This is really bad idea to write the logical expression to validate the variable’s value on the where clause, it might force the engine to use the index scan,

If .. Else is not harm to use in your query.. Don’t try to reduce the no of lines, check the performance..

Code Snippet

If @.myparam = 'ALL'

SELECT

uniqueID, lob, xdate

FROM

mytable

WHERE

xdate >= '2007-09-01'

ELSE

SELECT

uniqueID, lob, xdate

FROM

mytable

WHERE

xdate >= '2007-09-01' or lob = @.myparm

|||

Steve Kass wrote:

Your query can be written this way, I think:

SELECT uniqueID, lob, xdate

FROM mytable

WHERE (xdate >= '20070901')

AND (

@.myparm = 'ALL'

OR

lob = @.myparm

)

In SQL, CASE .. END is an expression, by the way, so it can't be used as you hoped in your post.

Steve - when @.myparm ='ALL', I want all of the records returned. The field (lob) does not actually contain the value 'ALL'.

I tried using a LIKE statement but found that nulls are not returned. For example, if @.myparm was populated with "%" and used in this query:

SELECT uniqueID, lob, xdate

FROM mytable

WHERE (xdate >= '20070901') and

lob LIKE @.myparm

then all records with a value in lob are returned but those will a null are not. I need to inlcude the records with a null.

Rob

|||

Manivannan.D.Sekaran wrote:

This is really bad idea to write the logical expression to validate the variable’s value on the where clause, it might force the engine to use the index scan,

If .. Else is not harm to use in your query.. Don’t try to reduce the no of lines, check the performance..

The problem with using the IF statement is the number of permutation when I have four variables.

IF @.myparm1 = 'ALL' and @.myparm2 <> 'ALL' and @.myparm3 <> 'ALL' and @.myparm4 <> 'ALL'

(query 1)

IF @.myparm1 <> 'ALL' and @.myparm2 = 'ALL' and @.myparm3 <> 'ALL' and @.myparm4 <> 'ALL'

(query 2)

IF @.myparm1 <> 'ALL' and @.myparm2 <> 'ALL' and @.myparm3 = 'ALL' and @.myparm4 <> 'ALL'

(query 3)

...

I think I'd wind up with 16 IF statements. While it should work, it would be very difficult to support.

Rob

|||

In your case the best solution is using the dynamic sql... Buliding the Where clause expression on the fly..

There are few limitations there while using the dynamic sql.. If you really need a best performance there is no compromise..

example,

Code Snippet

Declare @.SQL as Varchar(8000);

Declare @.Name as Varchar(8000);

Declare @.Type as Varchar(8000);

Declare @.Where as varchar(8000);

Set @.Name = null;

Set @.Type ='U'

Set @.SQL = 'Select * from Sysobjects Where 1=1'

Set @.Where = ''

IF @.Name is not NULL

Set @.Where = ' And Name=''' + @.Name + ''''

IF @.Type is NOT NULL

Set @.Where = @.Where + ' And Type=''' + @.Type + ''''

Exec (@.SQL + @.Where)

Code Snippet

Declare @.SQL as NVarchar(4000);

Declare @.Name as Varchar(8000);

Declare @.Type as Varchar(8000);

Declare @.Where as varchar(8000);

Set @.Name = NULL;

Set @.Type ='P'

Set @.SQL = 'Select * from Sysobjects Where 1=1'

Set @.Where = ''

IF @.Name is not NULL

Set @.Where = ' And Name=@.Name'

IF @.Type is NOT NULL

Set @.Where = @.Where + ' And Type=@.Type'

Set @.SQL = @.SQL + @.Where

Exec sp_executesql @.SQL, N'@.name varchar(100), @.type varchar(100)', @.name, @.type

|||Sorry, Rob. I misread your original intent, so let me try again. I think you want

1. If 'ALL' is passed: every row with xdate >= '20070901'
2. If 'ALL' is not passed: every row with xdate >= '20070901', as well as rows with lob = @.myparm, regardless of date.

First, a solution that assumes @.myparm is never NULL:

select uniqueID, lob, xdate
from mytable
where
(
@.myparm = 'ALL'
and
(xdate >= '20070901')
) or (
@.myparm <> 'ALL'
and
(@.myparm = lob or xdate >= '20070901')
)

Because you use NULL as a value for [lob], and you use @.myparm = NULL to select those rows, you can't rely on @.myparm = lob, which is not true when @.myparm and lob are both NULL. Unfortunately, you have to handle this separately, because T-SQL has no IS NOT DISTINCT FROM operator that means "are both equal or are both null". Whether you treat it as a third case or in the second case is up to you:

where
(
@.myparm = 'ALL'
and
(xdate >= '20070901')
) or (
@.myparm <> 'ALL'
and
(@.myparm = lob or xdate >= '20070901')
) or (
@.myparm IS NULL
and
(lob IS NULL or xdate >= '20070901')
)

So this is like what a CASE statement would be. The structure is

where
you are in case 1 and the where clause for that case holds
or
you are in case 2 and the where clause for that case holds
...

The problem with NULL is because a CASE expression would allow an OTHERWISE clause to handle both @.myparm <> 'ALL' and @.myparm IS NULL at once.

Note that I wrote the date without hyphens. Unfortunately, if xdate is [datetime] or [smalldatetime], SQL Server installations that use European and many other non-US localizations will interpret the date as you wrote it to mean January 9, 2007. I doubt you ever want that, and you can avoid a surprise by using the format I provided, or the other "safe" format '2007-09-01T00:00:00' (the T is required).

SK

|||

Steve Kass wrote:


select uniqueID, lob, xdate
from mytable
where
(
@.myparm = 'ALL'
and
(xdate >= '20070901')
) or (
@.myparm <> 'ALL'
and
(@.myparm = lob or xdate >= '20070901')
)

SK

Steve,

Thank you very much. This did the trick. It's amazing what a few AND & OR statements can do with the correct paranthesis.

I'm actually using these queres in SSRS as a data source. It took a couple of edits to get SSRS to take the paranthesis correctly as it want to "fix" them for you.

Rob

Conditional Where Clause w/ Case Statement Possible?

Greetings,

After many hours search many forums and many failed experiments, I figure it's time to turn to the experts.

I need to execute a query that changes the returned data based upon a parameter's value. In my example below, the lob field contains both text values and nulls.

SELECT uniqueID, lob, xdate

FROM mytable

WHERE

CASE WHEN @.myparam = 'ALL'

THEN

xdate >= '2007-09-01'

ELSE

xdate >= '2007-09-01' or

lob = @.myparm

END

I've experimented with various forms of the LIKE function, checking for null/not null and keep coming up blank.

I thought about using an IF statement and creating different versions of the entire statement, however, in real-life I need to do this with four fields using four parameters (one for each field). The permutations are a little too much.

Any ideas?

Rob

Your query can be written this way, I think:

SELECT uniqueID, lob, xdate

FROM mytable

WHERE (xdate >= '20070901')

AND (

@.myparm = 'ALL'

OR

lob = @.myparm

)

In general, you can probably write:

WHERE

(@.p = 'Option1' AND (<option 1 condition>))

OR

(@.p = 'Option 2' AND (<option 2 condition>))

OR

...

Be careful where parentheses go, so AND and OR don't associate differently than you want.

In SQL, CASE .. END is an expression, by the way, so it can't be used as you hoped in your post.

Steve Kass

Drew University

http://www.stevekass.com

|||

This is really bad idea to write the logical expression to validate the variable’s value on the where clause, it might force the engine to use the index scan,

If .. Else is not harm to use in your query.. Don’t try to reduce the no of lines, check the performance..

Code Snippet

If @.myparam = 'ALL'

SELECT

uniqueID, lob, xdate

FROM

mytable

WHERE

xdate >= '2007-09-01'

ELSE

SELECT

uniqueID, lob, xdate

FROM

mytable

WHERE

xdate >= '2007-09-01' or lob = @.myparm

|||

Steve Kass wrote:

Your query can be written this way, I think:

SELECT uniqueID, lob, xdate

FROM mytable

WHERE (xdate >= '20070901')

AND (

@.myparm = 'ALL'

OR

lob = @.myparm

)

In SQL, CASE .. END is an expression, by the way, so it can't be used as you hoped in your post.

Steve - when @.myparm ='ALL', I want all of the records returned. The field (lob) does not actually contain the value 'ALL'.

I tried using a LIKE statement but found that nulls are not returned. For example, if @.myparm was populated with "%" and used in this query:

SELECT uniqueID, lob, xdate

FROM mytable

WHERE (xdate >= '20070901') and

lob LIKE @.myparm

then all records with a value in lob are returned but those will a null are not. I need to inlcude the records with a null.

Rob

|||

Manivannan.D.Sekaran wrote:

This is really bad idea to write the logical expression to validate the variable’s value on the where clause, it might force the engine to use the index scan,

If .. Else is not harm to use in your query.. Don’t try to reduce the no of lines, check the performance..

The problem with using the IF statement is the number of permutation when I have four variables.

IF @.myparm1 = 'ALL' and @.myparm2 <> 'ALL' and @.myparm3 <> 'ALL' and @.myparm4 <> 'ALL'

(query 1)

IF @.myparm1 <> 'ALL' and @.myparm2 = 'ALL' and @.myparm3 <> 'ALL' and @.myparm4 <> 'ALL'

(query 2)

IF @.myparm1 <> 'ALL' and @.myparm2 <> 'ALL' and @.myparm3 = 'ALL' and @.myparm4 <> 'ALL'

(query 3)

...

I think I'd wind up with 16 IF statements. While it should work, it would be very difficult to support.

Rob

|||

In your case the best solution is using the dynamic sql... Buliding the Where clause expression on the fly..

There are few limitations there while using the dynamic sql.. If you really need a best performance there is no compromise..

example,

Code Snippet

Declare @.SQL as Varchar(8000);

Declare @.Name as Varchar(8000);

Declare @.Type as Varchar(8000);

Declare @.Where as varchar(8000);

Set @.Name = null;

Set @.Type ='U'

Set @.SQL = 'Select * from Sysobjects Where 1=1'

Set @.Where = ''

IF @.Name is not NULL

Set @.Where = ' And Name=''' + @.Name + ''''

IF @.Type is NOT NULL

Set @.Where = @.Where + ' And Type=''' + @.Type + ''''

Exec (@.SQL + @.Where)

Code Snippet

Declare @.SQL as NVarchar(4000);

Declare @.Name as Varchar(8000);

Declare @.Type as Varchar(8000);

Declare @.Where as varchar(8000);

Set @.Name = NULL;

Set @.Type ='P'

Set @.SQL = 'Select * from Sysobjects Where 1=1'

Set @.Where = ''

IF @.Name is not NULL

Set @.Where = ' And Name=@.Name'

IF @.Type is NOT NULL

Set @.Where = @.Where + ' And Type=@.Type'

Set @.SQL = @.SQL + @.Where

Exec sp_executesql @.SQL, N'@.name varchar(100), @.type varchar(100)', @.name, @.type

|||Sorry, Rob. I misread your original intent, so let me try again. I think you want

1. If 'ALL' is passed: every row with xdate >= '20070901'
2. If 'ALL' is not passed: every row with xdate >= '20070901', as well as rows with lob = @.myparm, regardless of date.

First, a solution that assumes @.myparm is never NULL:

select uniqueID, lob, xdate
from mytable
where
(
@.myparm = 'ALL'
and
(xdate >= '20070901')
) or (
@.myparm <> 'ALL'
and
(@.myparm = lob or xdate >= '20070901')
)

Because you use NULL as a value for [lob], and you use @.myparm = NULL to select those rows, you can't rely on @.myparm = lob, which is not true when @.myparm and lob are both NULL. Unfortunately, you have to handle this separately, because T-SQL has no IS NOT DISTINCT FROM operator that means "are both equal or are both null". Whether you treat it as a third case or in the second case is up to you:

where
(
@.myparm = 'ALL'
and
(xdate >= '20070901')
) or (
@.myparm <> 'ALL'
and
(@.myparm = lob or xdate >= '20070901')
) or (
@.myparm IS NULL
and
(lob IS NULL or xdate >= '20070901')
)

So this is like what a CASE statement would be. The structure is

where
you are in case 1 and the where clause for that case holds
or
you are in case 2 and the where clause for that case holds
...

The problem with NULL is because a CASE expression would allow an OTHERWISE clause to handle both @.myparm <> 'ALL' and @.myparm IS NULL at once.

Note that I wrote the date without hyphens. Unfortunately, if xdate is [datetime] or [smalldatetime], SQL Server installations that use European and many other non-US localizations will interpret the date as you wrote it to mean January 9, 2007. I doubt you ever want that, and you can avoid a surprise by using the format I provided, or the other "safe" format '2007-09-01T00:00:00' (the T is required).

SK

|||

Steve Kass wrote:


select uniqueID, lob, xdate
from mytable
where
(
@.myparm = 'ALL'
and
(xdate >= '20070901')
) or (
@.myparm <> 'ALL'
and
(@.myparm = lob or xdate >= '20070901')
)

SK

Steve,

Thank you very much. This did the trick. It's amazing what a few AND & OR statements can do with the correct paranthesis.

I'm actually using these queres in SSRS as a data source. It took a couple of edits to get SSRS to take the paranthesis correctly as it want to "fix" them for you.

Rob

|||in t-sql you can have conditional where clauses
sample:

select * from mytable
where
mycol = case when @.i = 1 then 1 else 2 end

Monday, March 19, 2012

Conditional summaring

Hi all
I'm trying to create a summery table of rain data that holds a record
for every 0.1mm of rain in the following format:

Station Name, Time, Value
A, 2002-12-03 14:44:41.000, 0.1
A, 2002-12-03 14:45:45.000, 0.1
A, 2002-12-03 14:49:45.000, 0.1
A, 2002-12-09 05:30:35.000, 0.1
A, 2002-12-09 05:30:37.000, 0.1
A, 2002-12-09 05:33:05.000, 0.1
B, 2002-12-09 05:32:47.000, 0.1
B, 2002-12-09 05:33:00.000, 0.1
B, 2002-12-09 05:35:00.000, 0.1
B, 2002-12-09 05:37:48.000, 0.1
...
B, 2003-02-09 01:32:47.000, 0.1
B, 2003-02-09 05:32:47.000, 0.1

The problem is that I need to count rain events for each station and
produce the starting and ending time of the event (based on the Time
field) and to summarize the amount of rain that fell during the event.
An "event" for that matter is a case where there is a gap of at least
12 hours with no rain before and after a series of rain measurements
(i.e., a rain storm). The data in the table is written in such a way
that each row hold the time where an amount on 0.1mm of rain was
counted by the rain gauge.

For example, the above date should produce:

Station Name, Start Time, End Time, Total rain
A, 2002-12-03 14:44:41.000, 2002-12-03 14:49:45.000, 0.3
A, 2002-12-09 05:30:35.000, 2002-12-09 05:33:05.000, 0.3
B, 2002-12-09 05:32:47.000, 2002-12-09 05:37:48.000, 0.3
B, 2003-02-09 01:32:47.000, 2003-02-09 05:32:47.000, 0.2

As a newbie to SQL I don't know if it can be done.

Many thanks,
IlikOn 14 Feb 2005 08:00:24 -0800, Ilik wrote:

>Hi all
>I'm trying to create a summery table of rain data that holds a record
>for every 0.1mm of rain in the following format:
>Station Name, Time, Value
>A, 2002-12-03 14:44:41.000, 0.1
>A, 2002-12-03 14:45:45.000, 0.1
>A, 2002-12-03 14:49:45.000, 0.1
>A, 2002-12-09 05:30:35.000, 0.1
>A, 2002-12-09 05:30:37.000, 0.1
>A, 2002-12-09 05:33:05.000, 0.1
>B, 2002-12-09 05:32:47.000, 0.1
>B, 2002-12-09 05:33:00.000, 0.1
>B, 2002-12-09 05:35:00.000, 0.1
>B, 2002-12-09 05:37:48.000, 0.1
>...
>B, 2003-02-09 01:32:47.000, 0.1
>B, 2003-02-09 05:32:47.000, 0.1
>The problem is that I need to count rain events for each station and
>produce the starting and ending time of the event (based on the Time
>field) and to summarize the amount of rain that fell during the event.
>An "event" for that matter is a case where there is a gap of at least
>12 hours with no rain before and after a series of rain measurements
>(i.e., a rain storm). The data in the table is written in such a way
>that each row hold the time where an amount on 0.1mm of rain was
>counted by the rain gauge.
>For example, the above date should produce:
>Station Name, Start Time, End Time, Total rain
>A, 2002-12-03 14:44:41.000, 2002-12-03 14:49:45.000, 0.3
>A, 2002-12-09 05:30:35.000, 2002-12-09 05:33:05.000, 0.3
>B, 2002-12-09 05:32:47.000, 2002-12-09 05:37:48.000, 0.3
>B, 2003-02-09 01:32:47.000, 2003-02-09 05:32:47.000, 0.2
>As a newbie to SQL I don't know if it can be done.

Hi Ilik,

It can be done, but it's quite complicated. You have to use several
tricks, then combine them into one query.

Trick 1: Find the start of a rain period. Each row for which no other row
exists with a time value in the preceding 12 hours marks the start of a
rain period. You can find these using NOT EXISTS or using an OUTER JOIN.
SELECT Station
, Time
FROM MyTable AS a
WHERE NOT EXISTS (SELECT *
FROM MyTable AS b
WHERE b.Station = a.Station
AND b.Time < a.Time
AND b.Time >= DATEADD(hour, -12, a.Time))
or
SELECT a.Station
, a.Time
FROM MyTable AS a
LEFT OUTER JOIN MyTable AS b
ON b.Station = a.Station
AND b.Time < a.Time
AND b.Time >= DATEADD(hour, -12, a.Time)
I'll use the NOT EXISTS version in the remainder of this message; if
performance is important for you, I'd advise you to test both versions.

Trick 2: Find the end of a rain period. This is basically the same
technique as trick 1.

Trick 3: Match up the start and end times of each rain period. For each
start, the matching end is the FIRST of all end's that occur AFTER that
start.
SELECT a.Station
, a.Time AS StartTime
, MIN(b.Time) AS EndTime
FROM MyTable AS a
INNER JOIN MyTable AS b
ON b.Station = a.Station
AND b.Time > a.Time
WHERE NOT EXISTS (SELECT *
FROM MyTable AS c
WHERE c.Station = a.Station
AND c.Time < a.Time
AND c.Time >= DATEADD(hour, -12, a.Time))
AND NOT EXISTS (SELECT *
FROM MyTable AS d
WHERE d.Station = b.Station
AND d.Time > b.Time
AND d.Time <= DATEADD(hour, +12, b.Time))
GROUP BY a.Station
, a.Time

Trick 4: Find all rows between start and end time of a rain period. This
can be done by using the result of the previous step as a derived table
and joining that to the original table, but in this case, I decided to
extend the result of the previous step with one correlated subquery.
SELECT a.Station
, a.Time AS StartTime
, MIN(b.Time) AS EndTime
,(SELECT SUM(e.Value)
FROM MyTable AS e
WHERE e.Station = a.Station
AND e.Time >= a.Time
AND e.Time <= MIN(b.Time)) AS TotalRain
FROM MyTable AS a
INNER JOIN MyTable AS b
ON b.Station = a.Station
AND b.Time > a.Time
WHERE NOT EXISTS (SELECT *
FROM MyTable AS c
WHERE c.Station = a.Station
AND c.Time < a.Time
AND c.Time >= DATEADD(hour, -12, a.Time))
AND NOT EXISTS (SELECT *
FROM MyTable AS d
WHERE d.Station = b.Station
AND d.Time > b.Time
AND d.Time <= DATEADD(hour, +12, b.Time))
GROUP BY a.Station
, a.Time

Note: all the queries above are untested. To get tested replies, you need
to post SQL that will recreate your tables and data on my system, as shown
in www.aspfaq.com/5006.

Best, Hugo
--

(Remove _NO_ and _SPAM_ to get my e-mail address)|||[posted and mailed, please reply in news]

Ilik (levyi@.walla.co.il) writes:
> The problem is that I need to count rain events for each station and
> produce the starting and ending time of the event (based on the Time
> field) and to summarize the amount of rain that fell during the event.
> An "event" for that matter is a case where there is a gap of at least
> 12 hours with no rain before and after a series of rain measurements
> (i.e., a rain storm). The data in the table is written in such a way
> that each row hold the time where an amount on 0.1mm of rain was
> counted by the rain gauge.

By no means a trivial problem. As Hugo said, CREATE TABLE and INSERT
statements are alwyas a good thing. Then again, the table was easy
to compose in this case, as were the INSERT statement. And your
narrative and sample data, was very good. Thanks!

Here is a multi-step approach. Maybe not the most elegant, but it
gives the correct result. If data volumes are large, performance
could be an issue, though.

A particular note on the datediff exercise. I do datediff per minute,
not per hour. This is because datediff(HOUR, '00:15:00', '12:10:10')
is 12, although it's not fully 12 hours. datediff always counts
cross boundaries. Also, I found that coalesce needed special care.
Originally I had 19000101, and 99991231, but that gave me overflow.

CREATE TABLE data(station char(1) NOT NULL,
time datetime NOT NULL,
value float NOT NULL,
CONSTRAINT pk_data PRIMARY KEY (station, time))
go
INSERT data (station, time, value)
SELECT 'A', '20021203 14:44:41.000', 0.1 UNION
SELECT 'A', '20021203 14:45:45.000', 0.1 UNION
SELECT 'A', '20021203 14:49:45.000', 0.1 UNION
SELECT 'A', '20021209 05:30:35.000', 0.1 UNION
SELECT 'A', '20021209 05:30:37.000', 0.1 UNION
SELECT 'A', '20021209 05:33:05.000', 0.1 UNION
SELECT 'B', '20021209 05:32:47.000', 0.1 UNION
SELECT 'B', '20021209 05:33:00.000', 0.1 UNION
SELECT 'B', '20021209 05:35:00.000', 0.1 UNION
SELECT 'B', '20021209 05:37:48.000', 0.1 UNION
SELECT 'B', '20030209 01:32:47.000', 0.1 UNION
SELECT 'B', '20030209 05:32:47.000', 0.1 UNION
SELECT 'B', '20030209 18:32:47.000', 0.1 UNION
SELECT 'B', '20030212 05:32:47.000', 0.1
go
CREATE TABLE #temp (station char(1) NOT NULL,
time datetime NOT NULL,
n int NOT NULL,
starttime datetime NULL,
endtime datetime NULL,
value float NOT NULL,
PRIMARY KEY (station, n))
go
INSERT #temp (station, time, value, n)
SELECT a.station, a.time, a.value,
(SELECT COUNT(*) + 1 FROM data b
WHERE a.station = b.station AND a.time > b.time)
FROM data a
go
UPDATE b
SET starttime = CASE WHEN datediff(minute,
coalesce(a.time, dateadd(DAY, -1, b.time)),
b.time) > 60*12
THEN b.time
END,
endtime = CASE WHEN datediff(minute,
b.time,
coalesce(c.time, dateadd(DAY, 1, b.time))) > 60*12
THEN b.time
END
FROM #temp b
LEFT JOIN #temp a ON a.station = b.station AND b.n - 1 = a.n
LEFT JOIN #temp c ON b.station = c.station AND b.n + 1 = c.n
go
UPDATE #temp
SET starttime = (SELECT MAX(b.starttime)
FROM #temp b
WHERE b.station = a.station
AND b.starttime < a.time)
FROM #temp a
WHERE a.starttime IS NULL
go
SELECT station, starttime, MAX(endtime), SUM(value)
FROM #temp
GROUP BY station, starttime
go
DROP TABLE #temp
DROP TABLE data

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

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||On Tue, 15 Feb 2005 21:28:13 +0000 (UTC), Erland Sommarskog wrote:

>By no means a trivial problem. As Hugo said, CREATE TABLE and INSERT
>statements are alwyas a good thing. Then again, the table was easy
>to compose in this case, as were the INSERT statement.

Hi Erland,

You're absolutely right. I guess this just shows that I'm lazy ;-)

I just stole your work to test my query and found one small error. The
corrected version (adapted to the table and column names you've chosen) is

SELECT a.station
, a.time AS Starttime
, MIN(b.time) AS Endtime
,(SELECT SUM(e.value)
FROM data AS e
WHERE e.station = a.station
AND e.time >= a.time
AND e.time <= MIN(b.time)) AS TotalRain
FROM data AS a
INNER JOIN data AS b
ON b.station = a.station
AND b.time >= a.time-- The change is in this line
WHERE NOT EXISTS (SELECT *
FROM data AS c
WHERE c.station = a.station
AND c.time < a.time
AND c.time >= DATEADD(hour, -12, a.time))
AND NOT EXISTS (SELECT *
FROM data AS d
WHERE d.station = b.station
AND d.time > b.time
AND d.time <= DATEADD(hour, +12, b.time))
GROUP BY a.station
, a.time

> And your
>narrative and sample data, was very good. Thanks!

I can only second that.

>Here is a multi-step approach. Maybe not the most elegant, but it
>gives the correct result. If data volumes are large, performance
>could be an issue, though.

I ran some quick tests for a first impression. Based on the difference
from start to end time for both queries, using the sample data provided,
it was too close to call. Increasing the amount of test data (copying the
insert two more times and changing the station names to C, D, E and F)
resulted in a small advantage for my query, but with so little test data,
that is not really saying anything.

With set statistics io on, my query used

Table 'data'. Scan count 151, logical reads 302, physical reads 0,
read-ahead reads 0.

And your code used

Table '#temp__(snip)'. Scan count 0, logical reads 86, physical reads 0,
read-ahead reads 0.
Table 'data'. Scan count 43, logical reads 86, physical reads 0,
read-ahead reads 0.

Table '#temp__(snip)'. Scan count 85, logical reads 254, physical reads 0,
read-ahead reads 0.
Table 'Worktable'. Scan count 1, logical reads 44, physical reads 0,
read-ahead reads 0.

Table '#temp__(snip)'. Scan count 25, logical reads 98, physical reads 0,
read-ahead reads 0.
Table 'Worktable'. Scan count 1, logical reads 26, physical reads 0,
read-ahead reads 0.

Table '#temp__(snip)'. Scan count 1, logical reads 2, physical reads 0,
read-ahead reads 0.

Adding up these numbers shows that your version appears to do quite some
more work than my version.

I'd be interested to hear from Ilik how the versions compare on his
system, with real data.

>A particular note on the datediff exercise. I do datediff per minute,
>not per hour. This is because datediff(HOUR, '00:15:00', '12:10:10')
>is 12, although it's not fully 12 hours. datediff always counts
>cross boundaries. Also, I found that coalesce needed special care.
>Originally I had 19000101, and 99991231, but that gave me overflow.

Why didn't you use DATEADD(hour, 12, a.time) > b.time, then? Wouldn't that
have solved all these issues?

Best, Hugo
--

(Remove _NO_ and _SPAM_ to get my e-mail address)|||I have to walk two dogs and install a Pergo floor this morning, so I
cannot work out the code in detail.

Can I assume that the measurements are collected by device that is
giving you a collection time? This means the data comes over time, and
it is a few microseconds behind the current time.

Instead of modeling the data collection form, model the final results:

CREATE TABLE Rainfall
(station_name CHAR(5) NOT NULL,
start_time DATETIME NOT NULL,
end_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
rain_accumulation DECIMAL (5,2) DEFAULT 0.00 NOT NULL,
CHECK (start_time < end_time),
PRIMARY KEY (station_name, start_time));

When a new reading comes in:

1) If it is within 12 hours of the start_time of the current row (i.e.
MAX(end_time) , then add 0.1 to the rain_accumulation and the end_time
CURRENT_TIMESTAMP in an UPDATE.

2) If it is more than 12 hours after the start_time of the current row,
then

2.1) update end_time to CURRENT_TIMESTAMP to close out the current
period.
2.2) insert new row with the new start_time, etc.

Something like this in pseudo-code.

CREATE PROCEDURE PostNewReading(@.my_station_name, @.new_reading_time)
AS
BEGIN
UPDATE Rainfall
SET end_time
= CASE WHEN <<less than 12 hours
FROM most recent>>
THEN @.new_reading_time
ELSE end_time END,
rain_accumulation
= CASE WHEN <<less than 12 hours
FROM most recent>>
THEN rain_accumulation + 0.1
ELSE rain_accumulation END;

INSERT INTO Rainfall
SELECT @.my_station_name, @.reading_time,
CURRENT_TIMESTAMP, 0.1
FROM Rainfall
WHERE <<reading more than 12 hours
FROM most recent>>;
END;

The idea is to put the procedural logic into CASE expressions in an
UPDATE and an INSERT statement. Use ELSE clauses to leave data
unchanged. No proprietary T-SQL control of flow stuff at all. No
tricky self-joins or cursors.|||Hi all
First, my sincere apologies for not replying earlier, but I was busy
over my head in the last couple of days with other projects.
In reply to CELKO, you're assuming that the data is being collected at
real time, but this is not the case. The data goes back a few decades
in some cases (starting at 1965), so I cannot evaluate it on entry.

As for Erland's solution, I run it only for a few minutes because of
his remark that performance can be an issue there. I tried running the
Hugo's query with the "NOT EXISTS" option. It run for two hours before
I stopped it... The second option ("LEFT OUTER JOIN ") I stopped after
15min ....
The table holding the data has over 1.3 million records, that besides
rain gauge data also has other data types (e.g., water conductivity,
water level, water chemistry etc.) in the "Class_Name" column. I didn't
mention this in my original post because I thought I could deal with it
after I'll get your help with the basic query, but now I see it is much
more complex then I thought. I added this to Hugo's query as you can
see below. So the efficiency of the query is an important issue here.
If you have any ideas on how to make it run faster?

Here is the query as I run it with both options:

--START
SELECT a.Location_Name
, a.Time AS StartTime
, MIN(b.Time) AS EndTime
,(SELECT SUM(e.Value)
FROM V_Cell AS e
WHERE e.Location_Name =
a.Location_Name
AND e.Class_Name = 'Rain'
AND e.Time >= a.Time
AND e.Time <= MIN(b.Time)) AS
TotalRain
FROM V_Cell AS a
INNER JOIN V_Cell AS b
ON b.Location_Name = a.Location_Name
AND b.Class_Name = 'Rain'
AND b.Time >= a.Time
-- WHERE NOT EXISTS (SELECT *
-- FROM V_Cell AS c
-- WHERE c.Location_Name =
a.Location_Name
LEFT OUTER JOIN V_Cell AS c
ON c.Location_Name = a.Location_Name
AND c.Class_Name = 'Rain'
AND c.Time < a.Time
AND c.Time >= DATEADD(hour, -12, a.Time)
-- AND NOT EXISTS (SELECT *
-- FROM V_Cell AS d
-- WHERE d.Location_Name =
b.Location_Name
LEFT OUTER JOIN V_Cell AS d
ON d.Location_Name = b.Location_Name
AND d.Class_Name = 'Rain'
AND d.Time > b.Time
AND d.Time <= DATEADD(hour, +12, b.Time)
GROUP BY a.Location_Name
, a.Time

--END

Many thanks,
Ilik|||On 17 Feb 2005 01:06:22 -0800, Ilik wrote:

(snip)
>If you have any ideas on how to make it run faster?

Hi Ilik,

I don't think there's much room for simplification of the query, so I'd
look into indexes. I don't expect my query to return results in a fraction
of a second, but two hours appears to be too much. I'm afraid that you
have no indexes on your table that can be used for this query.

In order for us to advise on this, we need to know the actual table
structure (as CREATE TABLE statement, **INCLUDING** all constraints [esp
primary key and unique!]) and all extra indexes you might have defined.
You might wish to run sp_help V_Cell to get a full report on all indexes
and constraints.

Another thing you could do is to run the index tuning wizard (ITW): load
my query in a QA window, select "Query" / "Index Tuning Wizard" and see
what it advises you. ITW is certainly not always perfect, but it never
hurts to check out what it comes up with.

Best, Hugo
--

(Remove _NO_ and _SPAM_ to get my e-mail address)|||Ilik (levyi@.walla.co.il) writes:
> As for Erland's solution, I run it only for a few minutes because of
> his remark that performance can be an issue there. I tried running the
> Hugo's query with the "NOT EXISTS" option. It run for two hours before
> I stopped it... The second option ("LEFT OUTER JOIN ") I stopped after
> 15min ....
> The table holding the data has over 1.3 million records, that besides
> rain gauge data also has other data types (e.g., water conductivity,
> water level, water chemistry etc.) in the "Class_Name" column. I didn't
> mention this in my original post because I thought I could deal with it
> after I'll get your help with the basic query, but now I see it is much
> more complex then I thought. I added this to Hugo's query as you can
> see below. So the efficiency of the query is an important issue here.
> If you have any ideas on how to make it run faster?

Your data volumes are certainly in par with what I expected. (No one
would have a table like that with only a few thousands of rows!) But
without test data available, it's difficult to post a solution that
tested for performance.

For my query batch, it could be an idea to let it run for a little
longer, and see what actually takes time.

Certainly there is all reason to review the indexing of the table, and
as Hugo said, posting the complete CREATE TABLE and CREATE INDEX
statement for the table may help.

One solution that cannot be ruled out completely, is to run a cursor
over the lot. That is by no means not going to be blinding fast, but
you can quite soon get a grip of when it will complete. (As you would
be able to see how much have been processed.) But that would really be
a last-ditch attempt if nothing else works.

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

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||>> The data goes back a few decades in some cases (starting at 1965),
so I cannot evaluate it on entry .. The table holding the data has over
1.3 million records, that besides rain gauge data also has other data
types (e.g., water conductivity, water level, water chemistry etc.) in
the "Class_Name" column. <<

Ouch! I think is a case where I would go with a cursor, since it
sounds like you will do this only once. That gives you one scan thru
the whole table.

Any other method I can think of would use a self-join to get the start
and finish times of each collection period. Even with indexing,
self-joins take time.|||"--CELKO--" <jcelko212@.earthlink.net> wrote in message
news:1108745004.509101.63100@.c13g2000cwb.googlegro ups.com...
> >> The data goes back a few decades in some cases (starting at 1965),
> so I cannot evaluate it on entry .. The table holding the data has over
> 1.3 million records, that besides rain gauge data also has other data
> types (e.g., water conductivity, water level, water chemistry etc.) in
> the "Class_Name" column. <<
> Ouch! I think is a case where I would go with a cursor, since it
> sounds like you will do this only once. That gives you one scan thru
> the whole table.
> Any other method I can think of would use a self-join to get the start
> and finish times of each collection period. Even with indexing,
> self-joins take time.

<Uninformed musings>
As others have stated, it is difficult to gauge the efficacy of the
suggestions without knowing more about the table structure.

Is it possible for the OP to extract the "Rain" records and create a new
table with appropriate indexing? He stated there are 1.3 million records
TOTAL but how many are "Rain" records and will it reduce the work to an
acceptable level for one of the aforementioned queries to complete?

How about a hybrid approach? What if you cursor-ed through the data by
"Station Name" and use one of the queries with the additional condition of
"Station Name"? I presume a table/list of the station names exist otherwise
you could "SELECT DISTINCT". As Hugo K. has demonstrated, the queries work
well enough for a small case which this would be especially if there is an
index on "station Name".
</Uninformed musings|||Hi all,
Thanks for your suggestions.
After a long consideration with my DB admin, we've decided to use the
curser approach as you suggest.
Currently, our db holds only about 9,000 records of type Rain but this
number is expected to grow
in the future since only a small part of the data has been introduced
into the database.
So using an all-at-once query of the data will be a very slow process.
Since I'm fairly new to SQLServer, I don't know how to run a script on
it directly. But since anyway
I only need to produce a web-report, I'm using MathLab for this (thou
VB or asp could do the job just as easy).

again, many thanks for your help,
Ilik

Conditional SQL Ajent Job execution

I have a job set to execute every 3 minutes. Only one instance of the
job should be running at any given time. If execution time exceeds 3
minutes - job should not start. Currently I have a flag in a
user-defined table that is set to 1 by the SP that is called by the
job when it begins, and reset back to 0 when it ends. The SP checks
the value of the flag, if it is currently = 1 then the SP exits.
The problem is that if the SP fails half-way through the flag is never
reset back to 0, thus preventing subsequent executions.
Is there a way to set the job to execute conditionally based on
whether or not another instance of same job is already running?I will probably add check the sysjobhistory to verify that
the job didn't fail:
select top 2 *
from sysjobhistory
where job_id = (select job_id from sysjobs
where name = <'Job Name'>)
order by run_date, convert(smalldatetime, (case len
(run_time)
when 1 then '00'+':'+'00'+':'+'0'+ right
(run_time,2)
when 2 then '00'+':'+'00'+':'+right
(run_time,2)
when 3 then '00'+':'+'0'+left(convert(char
(3), run_time), 1)+':'+right(run_time,2)
when 4 then '00'+':'+left(convert(char(4),
run_time), 2)+':'+right(run_time,2)
when 5 then '0'+left(convert(char(5),
run_time), 1)+':'+substring(convert(char(5), run_time), 2,
2)+':'+right(run_time,2)
when 6 then left(convert(char(6),
run_time), 2)+':'+substring(convert(char(6), run_time), 3,
2)+':'+right(run_time,2)
END)) desc
If the job failed, it should continue with the schedule:
Edgardo Valdez
MCSD, MCDBA, MCSE, MCP+I
http://www.edgardovaldez.us/
>--Original Message--
>I have a job set to execute every 3 minutes. Only one
instance of the
>job should be running at any given time. If execution
time exceeds 3
>minutes - job should not start. Currently I have a flag
in a
>user-defined table that is set to 1 by the SP that is
called by the
>job when it begins, and reset back to 0 when it ends.
The SP checks
>the value of the flag, if it is currently = 1 then the SP
exits.
>The problem is that if the SP fails half-way through the
flag is never
>reset back to 0, thus preventing subsequent executions.
>Is there a way to set the job to execute conditionally
based on
>whether or not another instance of same job is already
running?
>.
>|||You shouldn't need such flags etc. Agent will not start a job if it is still executing (from last
time).
--
Tibor Karaszi, SQL Server MVP
Archive at: http://groups.google.com/groups?oi=djq&as ugroup=microsoft.public.sqlserver
"Alexey Aksyonenko" <Alexey.Aksyonenko@.coanetwork.com> wrote in message
news:1449e414.0309300914.2af4241@.posting.google.com...
> I have a job set to execute every 3 minutes. Only one instance of the
> job should be running at any given time. If execution time exceeds 3
> minutes - job should not start. Currently I have a flag in a
> user-defined table that is set to 1 by the SP that is called by the
> job when it begins, and reset back to 0 when it ends. The SP checks
> the value of the flag, if it is currently = 1 then the SP exits.
> The problem is that if the SP fails half-way through the flag is never
> reset back to 0, thus preventing subsequent executions.
> Is there a way to set the job to execute conditionally based on
> whether or not another instance of same job is already running?

Sunday, March 11, 2012

Conditional Split - Compare DATETIME with constant

Hi,

I have to compare a DATETIME Field with '1/1/1900 12:00:00 AM". Which is default DATE TIME Value in SQL Server.

I did compare like

TRADEAGREEMENTFROMDATE != (DT_DBTIMESTAMP)(DATEPART("mm",(DT_DBTIMESTAMP)"1/1/1900 12:00:00 AM"))

but (DT_DBTIMESTAMP)(DATEPART("mm",(DT_DBTIMESTAMP)"1/1/1900 12:00:00 AM")) returns "12/31/1800 12:00:00:AM"

Thanks,

Aravind

So the value I got was slightly different.

(DT_DBTIMESTAMP)(DATEPART("mm",(DT_DBTIMESTAMP)"1/1/1900 12:00:00 AM")) = 31/12/1899 00:00:00

Why are you using DATEPART? Do you not just want -

(DT_DBTIMESTAMP)"1/1/1900" = 01/01/1900 00:00:00

That is the same as '1/1/1900 12:00:00 AM' which you asked for above, infact the time format is just my local settings UK rather than US, the values are exactly the same.

Wednesday, March 7, 2012

Conditional Formatting in Report Builder

Hi all!

I would like to know if Conditional Formatting in Report Builder is supported in Service Pack 2 CTP.

Thanks for your time.
Conditional formatting in Report Builder is not in SP2. We are considering adding it to a future release.

-Josh
|||

I am interested in conditional formatting for ad hoc reports as well. Is this something that will be available in the SQL 2008 release?

Thanks,

Lisa

Conditional Formating of axis labels(Urgent!)

Depending on the time interval, that is covered by the report and which will
be provided by parameters, the format of the x-axis labels should be e.g.
hh:mm:ss or dd.mm.yyyy. It seems to me, that the format can only be defined
statically. Why can't I use expressions here?
Any help is appreciated, thanks.You can certainly use expressions for the format code on x-axis labels.
However, make sure that the category grouping expressions (which get applied
to the x-axis) result in objects of type DateTime and not in strings. Format
codes won't have any effect on strings.
--
This posting is provided "AS IS" with no warranties, and confers no rights.
"Niklas" <Niklas@.discussions.microsoft.com> wrote in message
news:FD03A48E-AA5C-400E-815D-FDE48CD07CD0@.microsoft.com...
> Depending on the time interval, that is covered by the report and which
will
> be provided by parameters, the format of the x-axis labels should be e.g.
> hh:mm:ss or dd.mm.yyyy. It seems to me, that the format can only be
defined
> statically. Why can't I use expressions here?
> Any help is appreciated, thanks.

Saturday, February 25, 2012

Conditional Expression - i.e., IIF in Access

I have a query with a conditional expression that I can do just fine in Access but I am having a bear of a time trying to create a similar SQL View. Baiscally I want to say, if column A is null, use value B else use value C.

In Access the SQL is this:

SELECT IIf([Categorycode] Is Null,[tblconstituents].[CASNumber],[categorycode]) AS Casnumber, Sum(qryweldingrod3a.CFume) AS CFume, Sum(qryweldingrod3a.cslag) AS cSlag
FROM qryweldingrod3a INNER JOIN tblconstituents ON qryweldingrod3a.CASNumber = tblconstituents.CASNumber
GROUP BY IIf([Categorycode] Is Null,[tblconstituents].[CASNumber],[categorycode]);

But I know you can't use the IIF statement in SQL so I was trying CASE and was still coming up empty handed. Here is what I produced in SQL but it didn't work:

SELECT SUM(dbo.RecycleWR_qryWeldingRod3a_LBS.CFume) AS CFume, SUM(dbo.RecycleWR_qryWeldingRod3a_LBS.CSlag) AS cSlag,

CASNumber = CASE Type
WHEN categoryCode IS NULL THEN dbo.tblConstituents.CASNumber ELSE CategoryCode
END,
FROM dbo.tblConstituents INNER JOIN
dbo.RecycleWR_qryWeldingRod3a_LBS ON dbo.tblConstituents.CASNumber = dbo.RecycleWR_qryWeldingRod3a_LBS.CASNumber
GROUP BY dbo.RecycleWR_qryWeldingRod3a_LBS.CASNumber

Any ideas would be greatly appreciated.SELECT CASE WHEN ColA IS NULL THEN ColB ELSE ColC END|||Originally posted by Brett Kaiser
SELECT CASE WHEN ColA IS NULL THEN ColB ELSE ColC END

Well, when I do that, I get
"The Query Designer does not support the CASE SQL construct."

Can you even use CASE in a view?|||Also, I need to assign an alias to that column.|||What are you using?

Aren't you using query analyzer?

If you're using Access you may need to make it a PASS THRU query

SELECT CASE WHEN ColA IS NULL THEN ColB ELSE ColC END AS NewCol|||I was creating the query in VIEW but I got around it using a function. Took me awhile but its working fine now. Thanks for your help|||What do you mean in VIEW?

Are you doing this in Enterprise Manager?

I would recommend against that.|||Wether you use the designer in access or in EM, you'll loose the graphical representation of your query when you use CASE (and a bunch of other constructs). This is what the error message says. The query should run fine, anyway and you should see and be able to modify the sql source in access.
However, beware of the designer, especially if you have complex where clauses. All sorts of weird things may happen to your sql ;)|||What s/he said...

Use QA though for SQL Server development...

You'll have a lot less headaches...

Conditional Deletion in Replication

I am developing a transactional replication plan. I have one table
that most of the time I do not want to replicate deletions. There is
an exception to this rule. If the status_id of another table is false,
then the deletion should be replicated.
I have been having difficulty trying to put this condition in place. I
have tried modifying the sp_MSdel_dboTable stored procedure. I have
removed the if @.@.rowcount check and replication errors with the
messages:
-- Error executing a batch of commands. Retrying individual commands.
Eventually, it will fail with the message: if @.@.trancount > 0 rollback
tran
Any ideas on how to get around this issue?
Publisher: SQL 2000
Distributor: On a separate server
Subscriber: SQL 2005
Thanks for any help I can get.
You need to replicate an indexed view as a table on the subscriber. The
indexed view would only "show" rows which match the status_id in the other
table.
Hilary Cotter
Director of Text Mining and Database Strategy
RelevantNOISE.Com - Dedicated to mining blogs for business intelligence.
This posting is my own and doesn't necessarily represent RelevantNoise's
positions, strategies or opinions.
Looking for a SQL Server replication book?
http://www.nwsu.com/0974973602.html
Looking for a FAQ on Indexing Services/SQL FTS
http://www.indexserverfaq.com
"emreeves" <em_reeves@.lycos.com> wrote in message
news:1143754411.192208.291820@.i40g2000cwc.googlegr oups.com...
>I am developing a transactional replication plan. I have one table
> that most of the time I do not want to replicate deletions. There is
> an exception to this rule. If the status_id of another table is false,
> then the deletion should be replicated.
> I have been having difficulty trying to put this condition in place. I
> have tried modifying the sp_MSdel_dboTable stored procedure. I have
> removed the if @.@.rowcount check and replication errors with the
> messages:
> -- Error executing a batch of commands. Retrying individual commands.
> Eventually, it will fail with the message: if @.@.trancount > 0 rollback
> tran
> Any ideas on how to get around this issue?
>
> Publisher: SQL 2000
> Distributor: On a separate server
> Subscriber: SQL 2005
> Thanks for any help I can get.
>
|||Thanks! This sounds better than the next approach I was going to
try... creating a 1st Insert/Update trans replication, and a 2nd Delete
only with row filtering.
BTW - Thanks very much for your replication book. It has helped loads
this past few weeks.

Conditional Delete without Logging Transactions

Hi,
I need to delete many records in a table based on some conditions in the
where clause. This delete is taking plenty of time. How do I disable the
logging of transactions?
Thanks and Regards,
Prasanth
Hi
You cannot disable logging during deletion as in your case.
Divide the deletion into small transaction and try to run it. Also check out
if there are some indexes defined on the table, try to drop them and after
deletion to recreate them.
"Prasanth" <Prasanth@.discussions.microsoft.com> wrote in message
news:98AE9AA6-EF24-4334-AA8A-65E919119B5C@.microsoft.com...
> Hi,
> I need to delete many records in a table based on some conditions in the
> where clause. This delete is taking plenty of time. How do I disable the
> logging of transactions?
> --
> Thanks and Regards,
> Prasanth
|||Thanks, I will do with that.
"Uri Dimant" wrote:

> Hi
> You cannot disable logging during deletion as in your case.
> Divide the deletion into small transaction and try to run it. Also check out
> if there are some indexes defined on the table, try to drop them and after
> deletion to recreate them.
> "Prasanth" <Prasanth@.discussions.microsoft.com> wrote in message
> news:98AE9AA6-EF24-4334-AA8A-65E919119B5C@.microsoft.com...
>
>

Conditional Delete without Logging Transactions

Hi,
I need to delete many records in a table based on some conditions in the
where clause. This delete is taking plenty of time. How do I disable the
logging of transactions?
--
Thanks and Regards,
PrasanthHi
You cannot disable logging during deletion as in your case.
Divide the deletion into small transaction and try to run it. Also check out
if there are some indexes defined on the table, try to drop them and after
deletion to recreate them.
"Prasanth" <Prasanth@.discussions.microsoft.com> wrote in message
news:98AE9AA6-EF24-4334-AA8A-65E919119B5C@.microsoft.com...
> Hi,
> I need to delete many records in a table based on some conditions in the
> where clause. This delete is taking plenty of time. How do I disable the
> logging of transactions?
> --
> Thanks and Regards,
> Prasanth|||Thanks, I will do with that.
"Uri Dimant" wrote:
> Hi
> You cannot disable logging during deletion as in your case.
> Divide the deletion into small transaction and try to run it. Also check out
> if there are some indexes defined on the table, try to drop them and after
> deletion to recreate them.
> "Prasanth" <Prasanth@.discussions.microsoft.com> wrote in message
> news:98AE9AA6-EF24-4334-AA8A-65E919119B5C@.microsoft.com...
> > Hi,
> >
> > I need to delete many records in a table based on some conditions in the
> > where clause. This delete is taking plenty of time. How do I disable the
> > logging of transactions?
> > --
> > Thanks and Regards,
> > Prasanth
>
>

Friday, February 17, 2012

Concurrent call to a stored procedure

I have a multithread component which call to a stored procesure to do some
data processing. But the time for excuting the stored procedure increased
dramastly with the thread number. If the stored procesure is very simple
(only have insert statement ), it does not have this problem. Any
recommandations?Possibly blocking problems due to your transaction handling and the operatio
ns you do inside the
procedure. But we really need to know more about to code in your procedure t
o be able to comment
further.
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
Blog: http://solidqualitylearning.com/blogs/tibor/
"wdwedw" <wdwedw@.discussions.microsoft.com> wrote in message
news:07C3F51C-F994-4657-833F-9CA6C2676C4B@.microsoft.com...
>I have a multithread component which call to a stored procesure to do some
> data processing. But the time for excuting the stored procedure increased
> dramastly with the thread number. If the stored procesure is very simple
> (only have insert statement ), it does not have this problem. Any
> recommandations?

Tuesday, February 14, 2012

Concurrency issues in trees

Hi NG,
My indented Bill of Materials (BOM) report has been working for some time
now. It is time to deal with the issue of multiuser operations and
concurrency. My approach has been to use the tree spanning algorithm
suggested by Steve Kass. This stored procedure builds a table called
'ibom'. Next, my application reads ibom and places the result in the client
machine's XML file. Finally, a Crystal Report reads the XML file and prints
the report. This approach works fine as long as there is only one user
running the application. All hell would break loose if two or more users
were constructing the ibom table. The code at the end of this post shows my
C# application first building ibom and then reading ibom. No harm would
come if the ibom table was locked from the point of its creation until the
last row was read by my method WriteXML(). How do you set a lock in the
stored procedure TREESPAN (not shown in this post) and remove it after the
execution of WriteXML()? It is perfectly OK to DROP TABLE ibom after the
WriteXML(). Also note that this code will be infrequently run so locking
ibom will have little effect on performance. However, a garbaged ibom table
would be a disaster!
Thank you,
Bob
--
Robert Schuldenfrei
S. I. Inc.
32 Ridley Road
Dedham, MA 02026
bob@.s-i-inc.com
781/329-4828
private void LoadIbom(string treeSpan)
{
//--Call the stored procedure--
mcs3Connection.Open();
SqlCommand cmd = new SqlCommand(treeSpan, mcs3Connection);
cmd.CommandType = CommandType.Text;
SqlDataReader reader = cmd.ExecuteReader();
reader.Close();
mcs3Connection.Close();
}
//--Method to getting ibom table and writing XML--
private void WriteXML()
{
//--SQL code to get ibom table--
selectStmt = "SELECT "
+ "ps_PartIndex, "
+ "ps_ParentIndex, "
+ "ps_PartNo, "
+ "ps_Qty_Per, "
+ "Level, "
+ "ps_Effectivity, "
+ "ps_Add_Del, "
+ "ps_Ref, "
+ "path "
+ "FROM ibom "
+ "ORDER BY path ";
SqlCommand selectCmd = new SqlCommand(selectStmt, mcs3Connection);
mcs3Connection.Open();
try
{
bomReader = selectCmd.ExecuteReader();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + "\n\n"
+ ex.GetType().ToString() + "\n\n"
+ ex.StackTrace, "Exception");
mcs3Connection.Close();
}
while (bomReader.Read()) //read entire ibom table
{
strComponent = (string) bomReader["ps_PartNo"];
itemMaster = ItemMasterTbl.GetItemMaster(strComponent);
//format issues corrected here
intLevel = (int) bomReader["Level"];
if (intLevel == 0) BlankRow();
strComponent = " ".PadLeft(intLevel*3) + strComponent;
strLevel = intLevel.ToString();
decQtyPer = (decimal) bomReader["ps_Qty_Per"];
if (decQtyPer == 0) strQtyPer = "0.000000";
else strQtyPer = decQtyPer.ToString();
counter++;
xmlOut.WriteStartElement("PS1307");
xmlOut.WriteAttributeString("ps_component", strComponent);
xmlOut.WriteElementString("ps_parent", strDummy);
xmlOut.WriteElementString("ps_qty_per", strQtyPer);
xmlOut.WriteElementString("ps_desc", (string) itemMaster.IM_Desc);
xmlOut.WriteElementString("ps_phantom_flag", (string)
itemMaster.IM_phantom_flag);
xmlOut.WriteElementString("ps_UOM", (string) itemMaster.IM_UOM);
xmlOut.WriteElementString("ps_pur_mfg_code", (string)
itemMaster.IM_pur_mfg_code);
xmlOut.WriteElementString("ps_effectivity", (string)
bomReader["ps_Effectivity"]);
xmlOut.WriteElementString("ps_add_delete", (string)
bomReader["ps_Add_Del"]);
xmlOut.WriteElementString("ps_ref", (string) bomReader["ps_Ref"]);
xmlOut.WriteElementString("ps_level", strLevel);
xmlOut.WriteEndElement(); //PS1307
}
mcs3Connection.Close();
}
//----robert,
you can virtually partition your ibom table by adding a column (say, 'user')
with default of suser_sid() or suser_sname(), and reference this column in
where clause:
where user=suser_sname()
also, don't drop the ibom table, but rather delete ibom where
user=suser_sname()
hth
dean
"Robert Schuldenfrei" <schuldenfrei@.comcast.net> wrote in message
news:Y4SdnaXXUMpV14_fRVn-jg@.comcast.com...
> Hi NG,
> My indented Bill of Materials (BOM) report has been working for some time
> now. It is time to deal with the issue of multiuser operations and
> concurrency. My approach has been to use the tree spanning algorithm
> suggested by Steve Kass. This stored procedure builds a table called
> 'ibom'. Next, my application reads ibom and places the result in the
client
> machine's XML file. Finally, a Crystal Report reads the XML file and
prints
> the report. This approach works fine as long as there is only one user
> running the application. All hell would break loose if two or more users
> were constructing the ibom table. The code at the end of this post shows
my
> C# application first building ibom and then reading ibom. No harm would
> come if the ibom table was locked from the point of its creation until the
> last row was read by my method WriteXML(). How do you set a lock in the
> stored procedure TREESPAN (not shown in this post) and remove it after the
> execution of WriteXML()? It is perfectly OK to DROP TABLE ibom after the
> WriteXML(). Also note that this code will be infrequently run so locking
> ibom will have little effect on performance. However, a garbaged ibom
table
> would be a disaster!
> Thank you,
> Bob
> --
> Robert Schuldenfrei
> S. I. Inc.
> 32 Ridley Road
> Dedham, MA 02026
> bob@.s-i-inc.com
> 781/329-4828
> private void LoadIbom(string treeSpan)
> {
> //--Call the stored
procedure--
> mcs3Connection.Open();
> SqlCommand cmd = new SqlCommand(treeSpan, mcs3Connection);
> cmd.CommandType = CommandType.Text;
> SqlDataReader reader = cmd.ExecuteReader();
> reader.Close();
> mcs3Connection.Close();
> }
> //--Method to getting ibom table and writing
XML--
> private void WriteXML()
> {
> //--SQL code to get ibom
table--
> selectStmt = "SELECT "
> + "ps_PartIndex, "
> + "ps_ParentIndex, "
> + "ps_PartNo, "
> + "ps_Qty_Per, "
> + "Level, "
> + "ps_Effectivity, "
> + "ps_Add_Del, "
> + "ps_Ref, "
> + "path "
> + "FROM ibom "
> + "ORDER BY path ";
> SqlCommand selectCmd = new SqlCommand(selectStmt, mcs3Connection);
> mcs3Connection.Open();
> try
> {
> bomReader = selectCmd.ExecuteReader();
> }
> catch (Exception ex)
> {
> MessageBox.Show(ex.Message + "\n\n"
> + ex.GetType().ToString() + "\n\n"
> + ex.StackTrace, "Exception");
> mcs3Connection.Close();
> }
> while (bomReader.Read()) //read entire ibom table
> {
> strComponent = (string) bomReader["ps_PartNo"];
> itemMaster = ItemMasterTbl.GetItemMaster(strComponent);
> //format issues corrected here
> intLevel = (int) bomReader["Level"];
> if (intLevel == 0) BlankRow();
> strComponent = " ".PadLeft(intLevel*3) + strComponent;
> strLevel = intLevel.ToString();
> decQtyPer = (decimal) bomReader["ps_Qty_Per"];
> if (decQtyPer == 0) strQtyPer = "0.000000";
> else strQtyPer = decQtyPer.ToString();
> counter++;
> xmlOut.WriteStartElement("PS1307");
> xmlOut.WriteAttributeString("ps_component", strComponent);
> xmlOut.WriteElementString("ps_parent", strDummy);
> xmlOut.WriteElementString("ps_qty_per", strQtyPer);
> xmlOut.WriteElementString("ps_desc", (string) itemMaster.IM_Desc);
> xmlOut.WriteElementString("ps_phantom_flag", (string)
> itemMaster.IM_phantom_flag);
> xmlOut.WriteElementString("ps_UOM", (string) itemMaster.IM_UOM);
> xmlOut.WriteElementString("ps_pur_mfg_code", (string)
> itemMaster.IM_pur_mfg_code);
> xmlOut.WriteElementString("ps_effectivity", (string)
> bomReader["ps_Effectivity"]);
> xmlOut.WriteElementString("ps_add_delete", (string)
> bomReader["ps_Add_Del"]);
> xmlOut.WriteElementString("ps_ref", (string) bomReader["ps_Ref"]);
> xmlOut.WriteElementString("ps_level", strLevel);
> xmlOut.WriteEndElement(); //PS1307
> }
> mcs3Connection.Close();
> }
> //----
>|||Hi Dean and NG,
Thank you for the "very excellent" suggestion. I am an "old dog" and I have
trouble thinking in sets of rows. I am sure that will produce the desired
result with a trivial amount of additional code. This technique will come
in handy in a number of situations beyond my immediate issue.
Sincerely,
Bob
--
Robert Schuldenfrei
S. I. Inc.
32 Ridley Road
Dedham, MA 02026
bob@.s-i-inc.com
781/329-4828
"Dean" <deanv@.nospam.spin.hr> wrote in message
news:uSMRNc5EFHA.560@.TK2MSFTNGP15.phx.gbl...
> robert,
> you can virtually partition your ibom table by adding a column (say,
> 'user')
> with default of suser_sid() or suser_sname(), and reference this column in
> where clause:
> where user=suser_sname()
> also, don't drop the ibom table, but rather delete ibom where
> user=suser_sname()
> hth
> dean
> "Robert Schuldenfrei" <schuldenfrei@.comcast.net> wrote in message
> news:Y4SdnaXXUMpV14_fRVn-jg@.comcast.com...
> client
> prints
> my
> table

Concurrency in asp.net

Hi everybody,

I need to understand how concurrency excatlywork in asp.net. For example, I'm confused what happens if two users atthe same time try to access the same record in a table or even the samevariable. Do ASP.NET handle this , I mean by locking one user andletting the other to have access OR it's up to the programmer to writesome code to lock shared resources such as database , objects andvariables?

If it's up to the programmer to do this task, I appreciate if you can show me an example that clarifies that.

Thank you

ADO.NET uses a disconnected data model, meaning that in theory, nothings knows 2 users are accessing the same record at the same time. When you read a record, and the record is displayed, there is no connection left on the database. Therefore there is no "concurrency", so to speak, because for all general purpose, the users only see the record's -content-, not the record itself. This is required because the web is a stateless environment...you cannot keep a live connection to the server.

Thus, the only really effective way of handling this (there are other ways, but this is the all purpose one), is called Optimistic Concurrency. The record is read, and when you attempt to update it, ADO.NET (only IF you ask it to do so), will check if the record changed (by storing the original values) since it was read by the user. If it did, it will complain and tell you that someone else changed the record between the last time you read it and your update. Otherwise, it will write it normally.

If 2 people attempt to write the record at the exact same time ( I mean, there are 2 open connections on the same record at the exact same instant), then it is up to the DBMS to handle this, ADO.NET has no control over it. Usualy what will happen is one of the users will be given the go (first come first serve), and the second update will trigger the Optimistic Concurrency mechanism I just talked about.

|||

This article tell you how to Handling Concurrency Issues in .NET