Showing posts with label process. Show all posts
Showing posts with label process. Show all posts

Tuesday, March 27, 2012

Calling SqlDependency.Stop() in class destructor

Hey guys,

Have you ever tried to call the SqlDependency.Stop() method in a class destructor (C#)? It seems like the finalization process hangs after the call to the SqlDependency.Stop() method (for example the assignment after the SqlDependency.Stop() method call is never executed).

~Program()

{

if (!_finalized)

{

SqlDependency.Stop(NocConnectionString);

_finalized = false;

}

}

I tried to use the ADO.NET 2.0 tracing, and it shows that the SqlCommand.Cancel() method call throws an exception during finalization, but it’s not possible to intercept it. Do you have any clue about it or have you ever experinced the same problem?

Regards,

Dmytro Kryvko

Do you have the dependency object defined i a class variable ? Which modifier do you have defined for the variable, perhaps its not accessible through the destructor ? Which error do you get through the Stop method ?

HTH, Jens Suessmeyer.

http:/www.sqlserver2005.de

|||

Hi Jens,

No, I don't have any dependency objects defined as class variables. The question is different. If you have a following class, where for the test purposes starts the listener for receiving dependency change notifications and then immediately stop it, everything works fine.

class Test

{

private const string ConnectionString = "blah blah blah;";

public Test()

{

SqlDependency.Start(ConnectionString);

SqlDependency.Stop(ConnectionString);

}

}

If you try to stop a listener in the class destructor, the assignment (_finalized = false) after the SqlDependency.Stop() never gets executed. If you try to catch an exception thrown by the SqlDependency.Stop(), nothing is simply caught.

class Test

{

private const string ConnectionString = "blah blah blah;";

private bool _finalized = false;

public Test()

{

SqlDependency.Start(ConnectionString);

}

~Test()

{

if (!_finalized)

{

SqlDependency.Stop(ConnectionString);

_finalized = false;

}

}

}

Thanks a lot for your reply anyway!

Regards,

Dmytro

|||

Hi Dmytro,

If you want to do RAII in CLR you should implement IDisposable and stop the SqlDependency in the Dispose method. Then wrap your class instance in a using statement:

class Program

{

static void Main()

{

using (test = new Test())

{

// Doing work here..

}

}

}

class Test: IDisposable

{

private const string ConnectionString = "blah blah blah;";

private bool _finalized = false;

public Test()

{

SqlDependency.Start(ConnectionString);

}

void Dispose()

{

if (!_finalized)

{

SqlDependency.Stop(ConnectionString);

_finalized = true;

}

}

}

HTH,
~ Remus

|||

Hi Remus,

Thank you very much for your reply. Of course that way of recommend is right. I also experimented with implementing the IDisposable interface and stopping the SqlDependency during the disposal. However I’m talking about the case when it’s NOT POSSIBLE to wrap a class into the using statement.

In the example below I reproduced the case I describe. If you try to set a breakpoint on the (_disposed = true;) statement, it would never get called after something goes wrong during the SqlDependency.Stop() method execution.

class Program

{

static void Main(string[] args)

{

Test.Instance.DoNothing();

}

}

class Test : IDisposable

{

private const string ConnectionString = "blah blah blah;";

private static Test _test = null;

private bool _disposed = false;

private Test()

{

SqlDependency.Start(ConnectionString);

}

~Test()

{

Dispose(false);

}

public static Test Instance

{

get

{

if (null == _test)

_test = new Test();

return _test;

}

}

public void DoNothing()

{

}

private void Dispose(bool disposing)

{

if (!_disposed)

{

SqlDependency.Stop(ConnectionString);

_disposed = true;

}

}

#region IDisposable Members

public void Dispose()

{

Dispose(true);

GC.SuppressFinalize(this);

}

#endregion

}

If you try to enable the ADO.NET 2.0 tracing, you would see that an exception is thrown inside the SqlCommand.Cancel() method that it called at the time of finalization.

Regards,

Dmytro

|||

I don't know what are the various restrictions about the code allowed to run when the GC is evicting objects, but apparently you're hitting one. But the most important think is that the random moments when this happens (GC eviction) doesn't seem to be a good idea to place the SqlDependency.Stop in the first place. If your goal is to stop the SqlDependency infrastructure when the application exists (i.e. when the .exe finishes, or when a ASP app ends), then perhaps you should hook into the appopiate event (like Form.Closing, AppDomain.DomainUnload, Application.ApplicationExit etc).

HTH,
~ Remus

|||This thread is quite old, however it is the only Google hit for "SqlDependency.Stop DomainUnload" ;-)

I'm facing exactly the same problem. I'm creating a data access component that is caching some queries from a SQL Server 2005 database. The cache is invalidated using this shiny new, well not sooo new anymore, SqlDependency approach.

Because this component will be used in ASP.NET as well as in Forms and Windows Service applications, I'm searching for a common way to (internally) call SqlDependency.Stop().

Using a finalizer was my first idea, too, and this didn't work out. My second try was using an event handler for AppDomain.DomainUnload.

After all, this seems to work... But the built-in webserver in VS 2005 will hang for 4-5 minutes with 100% CPU while exeuting SqlDependy.Stop(). In fact, I can't remember of any other process blocking my machine (Pentium M laptop) reproducible so badly that I could hardly bring up Task Manager... I didn't expect this was possible from user-space and even managed code (SQL Server is running on another box.) During this time, even Performance Monitor refuses to log anything, so I can't say if there are a lot of Windows handles or .NET exceptions envolved or whatever...

Calling it from the Application_End event works fine (and takes only a few milliseconds), however this is specific to ASP.NET.

Any ideas?|||

Hi Markus,

I am not aware of any issue like the one you describe. I am not a .net expert by any stretch, but I would approach this like any other performance problem: perfcounters, F1 profiler, monitor traffic to SQL Server etc, to positively identify what is causing the high CPU consumption.

HTH,
~ Remus

|||Thank you very much for your reply. The high CPU usage does not occur on the remote SQL Server, but on my developer machine, so it is definitly a .NET issue. I only know that it happens with SqlDependency in combination with ASP.NET, however I can't yet say what exactly is causing the matter. I'll try to further narraw that down and let you know.

(Btw running anything like perfcounters doesn't help as it doesn't collect any data while SqlDependency.Stop(). At least with a single-core processor the system really hangs completly for a few minutes...)

However I would be glad to hear about any other approach to trigger SqlDependency.Stop than DomainUnload or finalizers.

Anyway, what would be the tradeoff of not stopping at all? While developing this happens all the time e.g. when you stop debugging. Will this leave SQL Server resources like queues etc. open forever, or will it be cleaned up sometime, e.g. with the next SQL Server restart?|||

You can start a perfcounter monitoring using logman.exe, it will capture all data even under most stressful conditions.

Each SqlDependency.Start () creates a service, a queue and a stored proc. It creates a dialog timer (BEGIN CONVERSATION TIMER) with itself. Normaly whenever this timer fires, the SqlDependency thread that has posted a RECEIVE verb will consume it and start another timer. If this timer message ever gets enqueued and there is no RECEIVE posted on the queue, the activated stored procedure associated with the queue will be invoked and this will clean up the service, the queue and the procedure itself. In other words, self-cleaning is provisioned, but the recommended way is still to call SqlDependency.Stop

HTH,
~ Remus

Calling SqlDependency.Stop() in class destructor

Hey guys,

Have you ever tried to call the SqlDependency.Stop() method in a class destructor (C#)? It seems like the finalization process hangs after the call to the SqlDependency.Stop() method (for example the assignment after the SqlDependency.Stop() method call is never executed).

~Program()

{

if (!_finalized)

{

SqlDependency.Stop(NocConnectionString);

_finalized = false;

}

}

I tried to use the ADO.NET 2.0 tracing, and it shows that the SqlCommand.Cancel() method call throws an exception during finalization, but it’s not possible to intercept it. Do you have any clue about it or have you ever experinced the same problem?

Regards,

Dmytro Kryvko

Do you have the dependency object defined i a class variable ? Which modifier do you have defined for the variable, perhaps its not accessible through the destructor ? Which error do you get through the Stop method ?

HTH, Jens Suessmeyer.

http:/www.sqlserver2005.de

|||

Hi Jens,

No, I don't have any dependency objects defined as class variables. The question is different. If you have a following class, where for the test purposes starts the listener for receiving dependency change notifications and then immediately stop it, everything works fine.

class Test

{

private const string ConnectionString = "blah blah blah;";

public Test()

{

SqlDependency.Start(ConnectionString);

SqlDependency.Stop(ConnectionString);

}

}

If you try to stop a listener in the class destructor, the assignment (_finalized = false) after the SqlDependency.Stop() never gets executed. If you try to catch an exception thrown by the SqlDependency.Stop(), nothing is simply caught.

class Test

{

private const string ConnectionString = "blah blah blah;";

private bool _finalized = false;

public Test()

{

SqlDependency.Start(ConnectionString);

}

~Test()

{

if (!_finalized)

{

SqlDependency.Stop(ConnectionString);

_finalized = false;

}

}

}

Thanks a lot for your reply anyway!

Regards,

Dmytro

|||

Hi Dmytro,

If you want to do RAII in CLR you should implement IDisposable and stop the SqlDependency in the Dispose method. Then wrap your class instance in a using statement:

class Program

{

static void Main()

{

using (test = new Test())

{

// Doing work here..

}

}

}

class Test: IDisposable

{

private const string ConnectionString = "blah blah blah;";

private bool _finalized = false;

public Test()

{

SqlDependency.Start(ConnectionString);

}

void Dispose()

{

if (!_finalized)

{

SqlDependency.Stop(ConnectionString);

_finalized = true;

}

}

}

HTH,
~ Remus

|||

Hi Remus,

Thank you very much for your reply. Of course that way of recommend is right. I also experimented with implementing the IDisposable interface and stopping the SqlDependency during the disposal. However I’m talking about the case when it’s NOT POSSIBLE to wrap a class into the using statement.

In the example below I reproduced the case I describe. If you try to set a breakpoint on the (_disposed = true;) statement, it would never get called after something goes wrong during the SqlDependency.Stop() method execution.

class Program

{

static void Main(string[] args)

{

Test.Instance.DoNothing();

}

}

class Test : IDisposable

{

private const string ConnectionString = "blah blah blah;";

private static Test _test = null;

private bool _disposed = false;

private Test()

{

SqlDependency.Start(ConnectionString);

}

~Test()

{

Dispose(false);

}

public static Test Instance

{

get

{

if (null == _test)

_test = new Test();

return _test;

}

}

public void DoNothing()

{

}

private void Dispose(bool disposing)

{

if (!_disposed)

{

SqlDependency.Stop(ConnectionString);

_disposed = true;

}

}

#region IDisposable Members

public void Dispose()

{

Dispose(true);

GC.SuppressFinalize(this);

}

#endregion

}

If you try to enable the ADO.NET 2.0 tracing, you would see that an exception is thrown inside the SqlCommand.Cancel() method that it called at the time of finalization.

Regards,

Dmytro

|||

I don't know what are the various restrictions about the code allowed to run when the GC is evicting objects, but apparently you're hitting one. But the most important think is that the random moments when this happens (GC eviction) doesn't seem to be a good idea to place the SqlDependency.Stop in the first place. If your goal is to stop the SqlDependency infrastructure when the application exists (i.e. when the .exe finishes, or when a ASP app ends), then perhaps you should hook into the appopiate event (like Form.Closing, AppDomain.DomainUnload, Application.ApplicationExit etc).

HTH,
~ Remus

|||This thread is quite old, however it is the only Google hit for "SqlDependency.Stop DomainUnload" ;-)

I'm facing exactly the same problem. I'm creating a data access component that is caching some queries from a SQL Server 2005 database. The cache is invalidated using this shiny new, well not sooo new anymore, SqlDependency approach.

Because this component will be used in ASP.NET as well as in Forms and Windows Service applications, I'm searching for a common way to (internally) call SqlDependency.Stop().

Using a finalizer was my first idea, too, and this didn't work out. My second try was using an event handler for AppDomain.DomainUnload.

After all, this seems to work... But the built-in webserver in VS 2005 will hang for 4-5 minutes with 100% CPU while exeuting SqlDependy.Stop(). In fact, I can't remember of any other process blocking my machine (Pentium M laptop) reproducible so badly that I could hardly bring up Task Manager... I didn't expect this was possible from user-space and even managed code (SQL Server is running on another box.) During this time, even Performance Monitor refuses to log anything, so I can't say if there are a lot of Windows handles or .NET exceptions envolved or whatever...

Calling it from the Application_End event works fine (and takes only a few milliseconds), however this is specific to ASP.NET.

Any ideas?|||

Hi Markus,

I am not aware of any issue like the one you describe. I am not a .net expert by any stretch, but I would approach this like any other performance problem: perfcounters, F1 profiler, monitor traffic to SQL Server etc, to positively identify what is causing the high CPU consumption.

HTH,
~ Remus

|||Thank you very much for your reply. The high CPU usage does not occur on the remote SQL Server, but on my developer machine, so it is definitly a .NET issue. I only know that it happens with SqlDependency in combination with ASP.NET, however I can't yet say what exactly is causing the matter. I'll try to further narraw that down and let you know.

(Btw running anything like perfcounters doesn't help as it doesn't collect any data while SqlDependency.Stop(). At least with a single-core processor the system really hangs completly for a few minutes...)

However I would be glad to hear about any other approach to trigger SqlDependency.Stop than DomainUnload or finalizers.

Anyway, what would be the tradeoff of not stopping at all? While developing this happens all the time e.g. when you stop debugging. Will this leave SQL Server resources like queues etc. open forever, or will it be cleaned up sometime, e.g. with the next SQL Server restart?|||

You can start a perfcounter monitoring using logman.exe, it will capture all data even under most stressful conditions.

Each SqlDependency.Start () creates a service, a queue and a stored proc. It creates a dialog timer (BEGIN CONVERSATION TIMER) with itself. Normaly whenever this timer fires, the SqlDependency thread that has posted a RECEIVE verb will consume it and start another timer. If this timer message ever gets enqueued and there is no RECEIVE posted on the queue, the activated stored procedure associated with the queue will be invoked and this will clean up the service, the queue and the procedure itself. In other words, self-cleaning is provisioned, but the recommended way is still to call SqlDependency.Stop

HTH,
~ Remus

sql

Thursday, March 22, 2012

Calling remote batch file using 'Execute process task'

I have a remote batch file on machine B that I need to execute using 'Execute process task' control from a package on machine A. The batch file uses pgp software and encrypts a file sitting on machine B itself. The reason why my batch file is sitting on machine B, is because the PGP software is on machine B.

If I execute the batch file by itself from machine B, the script runs fine. I refer the same batch file as a UNC path from my package on machine A. But that does not work since the 'Working directory' is still machine A. I can not set machine B's folder as the working dir because it does not accept UNC path. So I say, ok , let me map a path to that UNC location and map it as drive 'Z:\'. Certainly if I do so, I will be running the process on machine A and the batch file will look for the pgp software on machine A, and hence fail.

I have tried third party remote batch execution tools (PSEXEC) but have not had success, not because of SSIS limitations, but simply because the PGP executable when run through the PSEXEC tool, does not identify the location of the public keys on machine B and hence gives an encrytion failure.

How do I get the remote batch file to execute such that it executes with its own env? Is there a better remote execution tool I can try or are there any other features of SSIS I can use to get around this issue? I need the results of the batch file and hence do not want to make it an asyncronous process.

Thanks

Sumeet

PsExec will work for this purpose, and so will rsh and ssh implementation for Win32. Psexec is easier and you can use the "-e" parameter to configure alternate profile loading. Even if the environment from psexec were the minimal default user environment, just execute a remote command/script/executable which sets up the environment necessary prior to the pgp call.|||

Thanks. That helps. PsExec sends the alternate profile username/password as clear text. Can this be avoided in any way? I can not send account information to the PGP server as clear text. I am thinking about web service, but that has its own set of issues in executing a batch process, since the identiy of the executing process can not be changed (in 1.1)...

If someone can direct me to the user group where these questions can be better addressed, please let me know!

Thanks,

Sumeet

Tuesday, March 20, 2012

Calling child package out of process fails with Access Denied.

Has anyone ever used an Execute Package Task to call a child package, and the Execute Package Task's ExecuteOutOfProcess = True? Unless the account it runs under is an Administrator on the box, it fails for me with "Error 0x80070005 while loading package file "C:\program files\microsoft sql server\90\dts\Packages\ETL\Fact_SalesTransaction_Tracking.dtsx". Access is denied."

This is eating up hours and hours of my time, time we can't afford. Is anyone able to successfully call a child package out of process?

Unfortunately I have faced the same problem.

This only happens when you're executing the package from SQL Server Agent, or your account is of lower priveledges than anything but Administrator.

The only current solution to it, until ofcourse someone from microsoft fixes this problem, is to have your package run under the privelleges of a user in the Local Admin Group. Anything, and I mean anything less than that will cause you the same problem. I tried enabling ever single option, one by one, in the Local Security Policy, and nothing but adding the user that the SQL Server Agent executes in the context of, adding that user to the Local Admin group was the only solution.

Sorry for the bad news. But that's probably your only current solution as to what I know of.

|||

In this case it appears that the SQL Server Agent user account does not have access to the location of the package to be executed. If that access can be granted, then that should be effective.

However, you may not wish to give access to the Program Files folder - so you may wish to save the packages elsewhere in the file system. Alternatively, if file system access is tricky to provide, you may wish to store the packages in SQL Server and execute them from there. There are specific SSIS roles which can be used to control access to packages. See this interesting article from Kirk Haselden: http://www.sqlmag.com/Article/ArticleID/46723/sql_server_46723.html or this entry in Books Online: http://msdn2.microsoft.com/en-US/library/ms141053.aspx

A solution which enables package access with least privileges is certainly preferable to adding your Agent user to Local Admin.

Donald

Calling child package out of process fails with Access Denied.

Has anyone ever used an Execute Package Task to call a child package, and the Execute Package Task's ExecuteOutOfProcess = True? Unless the account it runs under is an Administrator on the box, it fails for me with "Error 0x80070005 while loading package file "C:\program files\microsoft sql server\90\dts\Packages\ETL\Fact_SalesTransaction_Tracking.dtsx". Access is denied."

This is eating up hours and hours of my time, time we can't afford. Is anyone able to successfully call a child package out of process?

Unfortunately I have faced the same problem.

This only happens when you're executing the package from SQL Server Agent, or your account is of lower priveledges than anything but Administrator.

The only current solution to it, until ofcourse someone from microsoft fixes this problem, is to have your package run under the privelleges of a user in the Local Admin Group. Anything, and I mean anything less than that will cause you the same problem. I tried enabling ever single option, one by one, in the Local Security Policy, and nothing but adding the user that the SQL Server Agent executes in the context of, adding that user to the Local Admin group was the only solution.

Sorry for the bad news. But that's probably your only current solution as to what I know of.

|||

In this case it appears that the SQL Server Agent user account does not have access to the location of the package to be executed. If that access can be granted, then that should be effective.

However, you may not wish to give access to the Program Files folder - so you may wish to save the packages elsewhere in the file system. Alternatively, if file system access is tricky to provide, you may wish to store the packages in SQL Server and execute them from there. There are specific SSIS roles which can be used to control access to packages. See this interesting article from Kirk Haselden: http://www.sqlmag.com/Article/ArticleID/46723/sql_server_46723.html or this entry in Books Online: http://msdn2.microsoft.com/en-US/library/ms141053.aspx

A solution which enables package access with least privileges is certainly preferable to adding your Agent user to Local Admin.

Donald

Sunday, March 11, 2012

Calling a stored procedure and pass parameter one by one

Hi,

I need to create a batch process which calls a stored procedure.

Here's the scenario.

I have 3 tables

Theater - TheaterId, TheaterName, Revenues,locationid, stateid
State - StateId, StateName
Location - LocationId, LocationName, StateId

There is a stored procedure spoc_updateTheater that accepts the state and location id and runs a set of sql statements against the theater table. However i want this to run for all the locations in a state one by one. There are some 700 locations in 45 states. How do i pass the location and state id one by one to the stored proc. Can i call this from a commandline or run it as batch process?

vidkshi

You will have iterate through the filtered data of the first procedure and execute the procedure one by one, the is no command to do this you will have to do that manually. Would look like the following pseudo code.

TableContent = YouSelectquery

Loop throught the data and pick one row per iteration
{

Execute your procedure with the values from the picked rows.

}

You can either do this using a cursor (preferable fast forward / read ony if you do not want to change anything) or use a tamp table.

Jens K. Suessmeyer

http://www.sqlserver2005.de

|||

Hi,

I will appreciate if someone could tell me the sql for it :

Here's the Theater table and the data. I want to loop through every state and location in the state/location tables and pass that stateid locationid to the stored proc.

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Theater]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Theater](
[TheaterId] [int] NULL,
[TheaterName] [nchar](10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[Revenues] [bigint] NULL,
[StateId] [int] NULL,
[LocationId] [int] NULL
)
END
GO
INSERT [dbo].[Theater] ([TheaterId], [TheaterName], [Revenues], [StateId], [LocationId]) VALUES (1, N'T1 ', 10000, 1, 1)
INSERT [dbo].[Theater] ([TheaterId], [TheaterName], [Revenues], [StateId], [LocationId]) VALUES (2, N'T2 ', 2333, 1, 1)
INSERT [dbo].[Theater] ([TheaterId], [TheaterName], [Revenues], [StateId], [LocationId]) VALUES (3, N'T3 ', 234234, 1, 1)
INSERT [dbo].[Theater] ([TheaterId], [TheaterName], [Revenues], [StateId], [LocationId]) VALUES (4, N'T4 ', 43454, 1, 2)
INSERT [dbo].[Theater] ([TheaterId], [TheaterName], [Revenues], [StateId], [LocationId]) VALUES (5, N'T5 ', 4454, 1, 2)
INSERT [dbo].[Theater] ([TheaterId], [TheaterName], [Revenues], [StateId], [LocationId]) VALUES (6, N'T6 ', 11132, 2, 1)
INSERT [dbo].[Theater] ([TheaterId], [TheaterName], [Revenues], [StateId], [LocationId]) VALUES (7, N'T7 ', 345, 2, 1)
INSERT [dbo].[Theater] ([TheaterId], [TheaterName], [Revenues], [StateId], [LocationId]) VALUES (8, N'T8 ', 675445, 2, 2)
INSERT [dbo].[Theater] ([TheaterId], [TheaterName], [Revenues], [StateId], [LocationId]) VALUES (9, N'T9 ', 344556, 3, 1)
INSERT [dbo].[Theater] ([TheaterId], [TheaterName], [Revenues], [StateId], [LocationId]) VALUES (10, N'T10 ', 23234, 3, 1)

vidkshi|||

What about:

Code Snippet

CREATE PROCEDURE spUpdateTheater

/*

Written by Jens K. Suessmeyer (c) http://www.sqlserver2005.de

*/

AS

BEGIN

SET NOCOUNT ON

DECLARE @.TheaterData Table

(

COUNTER INT IDENTITY(1,1),

Theaterid INT NULL,

StateId INT NULL

)

DECLARE @.ROWCOUNT INT

DECLARE @.I INT

SET @.I = 1

DECLARE @.Theaterid INT

DECLARE @.StateId INT

INSERT INTO @.TheaterData

(

Theaterid,

StateId

)

SELECT DISTINCT

TheaterId,

Stateid

FROM Theather

SET @.ROWCOUNT = @.@.ROWCOUNT

WHILE @.I <= @.ROWCOUNT

BEGIN

SELECT

@.Theaterid = TheaterId,

@.StateId = Stateid

FROM @.TheaterData

WHERE COUNTER = @.ROWCOUNT

EXEC spExecuteYourUpdateProcedure @.Theaterid,@.StateId

SET @.I = @.I +1

END

END

Jens K. Suessmeyer

http://www.sqlserver2005.de

|||

Hi,

Thanks for the code. I was wondering why you added the theater id and stateid in the temp table whereas it had to be stateid and locationid. Anyways i changd your query to look like this. I also tried running your stored proc as is but with no results.

Code Snippet

ALTER PROCEDURE [dbo].[spUpdateTheater]
/*

Written by Jens K. Suessmeyer (c) http://www.sqlserver2005.de

*/

AS

BEGIN

SET NOCOUNT ON

DECLARE @.TheaterData Table

(

COUNTER INT IDENTITY(1,1),

Locationid INT NULL,

StateId INT NULL

)

DECLARE @.ROWCOUNT INT

DECLARE @.I INT

SET @.I = 1

DECLARE @.Locationid INT

DECLARE @.StateId INT

INSERT INTO @.TheaterData

(

Locationid,

StateId

)

SELECT DISTINCT

LocationId,

Stateid

FROM Theater

select * from @.TheaterData

SET @.ROWCOUNT = @.@.ROWCOUNT

WHILE @.I <= @.ROWCOUNT

BEGIN

SELECT

@.Locationid = LocationId,

@.StateId = Stateid

FROM @.TheaterData

WHERE COUNTER = @.ROWCOUNT

EXEC spoc_Theater @.StateId, @.Locationid

SET @.I = @.I +1

END

END

My store proc spoc_updatetheater looks like this

Code Snippet

ALTER proc [dbo].[spoc_Theater]
@.stateid int,
@.locid int
as
update theater
set revenues = 20000
where stateid = @.stateid and locationid = @.locid
and revenues > 10000

I tried running it however I see there is no change in the Theater table after the query executes.

Any reasons?

Vids

|||

Yes, you are right and in addition you should change the

Code Snippet

WHERE COUNTER = @.ROWCOUNT

to

Code Snippet

WHERE COUNTER = @.I

Jens K. Suessmeyer

http://www.sqlserver2005.de
|||

Cool. thanks.

you also mentioned that the same query could be written using a cursor. What advantage will i get.

In this query we are creating a temporary table, filling data and looping through it. I expect around 5000 different combinations of state and location id in this temporary table. Will it be ok from a performance point to use the temporary table?

Cant i just use the location table as it will contain a distinct location and state combination. So instead of the temp table, i just loop through the location table and execute the proc for each combination of location and state. How will we do this using a cursor and how will it improve performance?

Vidkshi.

|||

I guess you won′t recognize the difference with 5000 rows. You can sure switch over to the locations tables.

Jens K. Suessmeyer

http://www.sqlserver2005.de

|||I don't have an answer to your question but you might want to consider removing the stateid from your Theater table as it violates 3rd normal form.

Theater - TheaterId, TheaterName, Revenues,locationid, stateid
State - StateId, StateName
Location - LocationId, LocationName, StateId

Calling a Data Pump task from DTS?

I have a vbscript to read all files from a directory and, if the file
is valid, I would like my DTS to process it. I tried using the
vbscript as an ActiveX workflow script in the DTS, but it does not
execute the data pump until it has completed looping through all the
files, so only the last file read is sucked into the database
(utilizing a global variable as the filename). Is there a way to
execute the data pump task from within the activex script? I can't
seem to find any documentation about executing a DTS task.

Basically, the workflow I want is:

1)Read files from directory (the number and names may change each
time). (done with vbs)

2)For each file, send it through the transformation into the database.

3)When the information is in the database, append a date to the file
and move it to the archive folder. (done with vbs)

If I am going about this the wrong way and you see something that is
not obvious to me, please let me know.

Thanks in advance!Hi

This may help:
http://www.sqldts.com/default.aspx?246

John

<noelle.bond@.gmail.com> wrote in message
news:1128110995.716126.283160@.g47g2000cwa.googlegr oups.com...
>I have a vbscript to read all files from a directory and, if the file
> is valid, I would like my DTS to process it. I tried using the
> vbscript as an ActiveX workflow script in the DTS, but it does not
> execute the data pump until it has completed looping through all the
> files, so only the last file read is sucked into the database
> (utilizing a global variable as the filename). Is there a way to
> execute the data pump task from within the activex script? I can't
> seem to find any documentation about executing a DTS task.
> Basically, the workflow I want is:
> 1)Read files from directory (the number and names may change each
> time). (done with vbs)
> 2)For each file, send it through the transformation into the database.
> 3)When the information is in the database, append a date to the file
> and move it to the archive folder. (done with vbs)
> If I am going about this the wrong way and you see something that is
> not obvious to me, please let me know.
> Thanks in advance!|||Thanks so much! I'll give it a try.|||noelle.bond@.gmail.com wrote:

> Thanks so much! I'll give it a try.

Just be forewarned, the DTS designer has a big disconnect between what
it shows you as the name of a DTS step and what actually needs to be
used in your VBScript code to refer to it as...

Thursday, March 8, 2012

Call to Gurus -- SQLDateTimeAPI

Hey gurus ...

I am in the process of writing a DateTime API for SQL Server 2000 ...
Here's what I have come up with so far ...


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_FirstDayOfMonth]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_FirstDayOfMonth]
GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_LastDayOfMonth]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_LastDayOfMonth]
GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_LastWorkingDayOfMonth]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_LastWorkingDayOfMonth]
GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_WorkingDaysBetweenDates]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_WorkingDaysBetweenDates]
GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[usp_PopulateTimeSeed]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[usp_PopulateTimeSeed]
GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[TimeSeed]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[TimeSeed]
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

CREATE Function
fn_FirstDayOfMonth (@.SearchDate datetime)
Returns
Datetime
as
Begin
Declare @.ReturnDate datetime

Select
@.ReturnDate = CalendarDate
from
TimeSeed
where
CalendarYear = Year(@.SearchDate)
and CalendarMonth = Month(@.SearchDate)
and DateOfMonth = 1

Return @.ReturnDate
End

GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

Create Function
fn_LastDayOfMonth (@.SearchDate datetime)
Returns
Datetime
as
Begin
Declare @.ReturnDate datetime

Select
@.ReturnDate = Max(CalendarDate)
from
TimeSeed
where
CalendarYear = Year(@.SearchDate)
and CalendarMonth = Month(@.SearchDate)
Return @.ReturnDate
End

GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

Create Function
fn_LastWorkingDayOfMonth (@.SearchDate datetime)
Returns
Datetime
as
Begin
Declare @.ReturnDate datetime

Select
@.ReturnDate = Max(CalendarDate)
from
TimeSeed
where
CalendarYear = Year(@.SearchDate)
and CalendarMonth = Month(@.SearchDate)
and WorkingDayFlag = 1
Return @.ReturnDate
End
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

CREATE Function
fn_WorkingDaysBetweenDates (@.SearchDate1 datetime, @.SearchDate2 datetime)
Returns
int
as
Begin
Declare @.CountDate int

Select
@.CountDate = Count(CalendarDate)
from
TimeSeed
where
CalendarDate >= @.SearchDate1
and CalendarDate <= @.SearchDate2
and WorkingDayFlag = 1
Return @.CountDate
End
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
CREATE TABLE [dbo].[TimeSeed] (
[CalendarDate] [datetime] NOT NULL ,
[DateOfMonth] [int] NOT NULL ,
[DayOfMonth] [varchar] (12) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[CalendarMonth] [int] NOT NULL ,
[CalendarYear] [int] NOT NULL ,
[FiscalYear] [varchar] (9) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[FiscalMonth] [int] NOT NULL ,
[WorkingDayFlag] [bit] NOT NULL ,
[WorkingHours] [int] NOT NULL ,
[WeekOfYear] [int] NOT NULL ,
[WeekOfMonth] [int] NOT NULL
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[TimeSeed] WITH NOCHECK ADD
CONSTRAINT [PK_TimeSeed] PRIMARY KEY CLUSTERED
(
[CalendarDate]
) ON [PRIMARY]
GO
CREATE INDEX [IX_TimeSeed] ON [dbo].[TimeSeed]([DateOfMonth]) ON [PRIMARY]
GO
CREATE INDEX [IX_TimeSeed_1] ON [dbo].[TimeSeed]([CalendarYear]) ON [PRIMARY]
GO
CREATE INDEX [IX_TimeSeed_2] ON [dbo].[TimeSeed]([CalendarMonth]) ON [PRIMARY]
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
Create Procedure usp_PopulateTimeSeed
as
Declare
@.StartDate datetime
Select
@.StartDate = '19000101'
Set DateFirst 1
While @.StartDate <= '21001231'
begin
insert into TimeSeed
(
IntDate
,CalendarDate
,DateOfMonth
,DayOfMonth
,CalendarMonth
,CalendarYear
,FiscalYear
,FiscalMonth
,WorkingDayFlag
,WorkingHours
,WeekOfYear
,WeekOfMonth
)
Select
Cast (@.StartDate as int)
,@.StartDate
,Day(@.StartDate)
,Datepart(DW,@.StartDate)
,Month(@.StartDate)
,Year(@.StartDate)
,Case
When Month(@.StartDate) <= 3
Then Year(@.StartDate) - 1
Else Year(@.StartDate)
End
,Case
When Month(@.StartDate) <= 3
Then Month(@.StartDate) + 9
Else Month(@.StartDate) - 3
End
,Case
When Datepart(DW,@.StartDate) in (1,7)
Then 0
else 1
End
,8
,Datepart(wk,@.StartDate)
,(Day(@.StartDate)%7)+1

Select
@.StartDate = Dateadd(dd,1,@.Startdate)
End
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO


Here's what has me stumped

I'd like to calculate the hours difference for a given start and end datetime in SQL server. Certainly function datediff() can do the job but the tricky part is that the hours calculation should be based on 8 hrs / per business day (from 8:00am to 5:00pm), and weekends (Saturdays and Sundays) are excluded as well.

For example:
start time: 11/10/04 4:00pm
end time: 11/11/04 8:00 am
then the hours difference should be only 1 hour. (if there is fraction, then round to nearest hour).


Now ... remember that the table TimeFeed is modifiable and can be changed to suit our needs.

Any ideas ?

Also ... you can all chip in with your own functions ...You forgot holidaze, daylight savings time (which is different all over the world)...what else...

I think you're still going to needs a "schedule" table...|||I am planning to have a holidaze table .... just started on this API about two hours back ... jump in with ideas ...|||Just to bring this back to the first page ... bump !!!

Wednesday, March 7, 2012

call sp_MSmakegeneration (?)

Hi ,
I have set up merge replication between two servers. The process goes
through all the
bulk copying and applying of some scripts and then end on the error:
The process could not make a generation at the 'Subscriber'.
Last Command {call sp_MSmakegeneration (?)}
I have no idea why this is happening. Any ideas?
Regards,
Swati
1. Run DBCC CHECKDB('dbname')
against the publisher and subscriber db to check for corruption.
2. Also, the results of sp_helpserver should show a serverid of 0 for the
local server, is this what you are seeing?
For example if my SQL server name is "ABC\inst1", sp_helpserver should show:
name id
-- --
ABC\inst1 0
3. Are you running other merge agents simultaneously? If so, try stopping
all other agents and sqlagent jobs, and see if that alleviates the issue.
Fany Vargas
Microsoft Corporation
This posting is provided "AS IS" with no warranties, and confers no rights.
Are you secure? For information about the Strategic Technology Protection
Program and to order your FREE Security Tool Kit, please visit
http://www.microsoft.com/security.
Microsoft highly recommends that users with Internet access update their
Microsoft software to better protect against viruses and security
vulnerabilities. The easiest way to do this is to visit the following
websites:
http://www.microsoft.com/protect
http://www.microsoft.com/security/guidance/default.mspx
|||On publisher
sp_helpserver is showing as serverid = 0 and on subscriber it is 1 , now
what should I do ?
dbcc checkdb doesnot shows any corrupted table
Regards,
Swati
"Fany Vargas [MSFT]" <fanyv@.online.microsoft.com> wrote in message
news:l#$TqRj4EHA.3512@.cpmsftngxa10.phx.gbl...
> 1. Run DBCC CHECKDB('dbname')
> against the publisher and subscriber db to check for corruption.
> 2. Also, the results of sp_helpserver should show a serverid of 0 for the
> local server, is this what you are seeing?
> For example if my SQL server name is "ABC\inst1", sp_helpserver should
show:
> name id
> -- --
> ABC\inst1 0
>
> 3. Are you running other merge agents simultaneously? If so, try stopping
> all other agents and sqlagent jobs, and see if that alleviates the issue.
> Fany Vargas
> Microsoft Corporation
> This posting is provided "AS IS" with no warranties, and confers no
rights.
> Are you secure? For information about the Strategic Technology Protection
> Program and to order your FREE Security Tool Kit, please visit
> http://www.microsoft.com/security.
> Microsoft highly recommends that users with Internet access update their
> Microsoft software to better protect against viruses and security
> vulnerabilities. The easiest way to do this is to visit the following
> websites:
> http://www.microsoft.com/protect
> http://www.microsoft.com/security/guidance/default.mspx
>
|||Pls help ! It's quiet urgent .. i am unable to replicate any data..
Regards,
Swati
"swati" <swati.zingade@.ugamsolutions.com> wrote in message
news:#lWC3gy4EHA.1596@.tk2msftngp13.phx.gbl...[vbcol=seagreen]
> On publisher
> sp_helpserver is showing as serverid = 0 and on subscriber it is 1 , now
> what should I do ?
> dbcc checkdb doesnot shows any corrupted table
> Regards,
> Swati
>
> "Fany Vargas [MSFT]" <fanyv@.online.microsoft.com> wrote in message
> news:l#$TqRj4EHA.3512@.cpmsftngxa10.phx.gbl...
the[vbcol=seagreen]
> show:
stopping[vbcol=seagreen]
issue.[vbcol=seagreen]
> rights.
Protection
>
|||I want to confirm that what you mean is that on the subscriber you do not
see a SRVID of 0 for the subscriber server when running sp_helpserver on
the subscriber. So for example if my subscriber server is called
SUBSCRIBER1\INST1, and sp_helpserver on this subscriber shows:
name id
-- --
SUBSCRIBER1\INST1 0
nameofpublisherserver 1
then there is no problem, however if you see something like:
name id
-- --
SUBSCRIBER1\INST1 2
nameofpublisherserver 1
then there is a problem because you should have server ID 0 for the local
server. If that is the case you run the following to correctly set the
local server name :
-- Drop the server with incorrect name
EXEC sp_dropserver @.server='SUBSCRIBER1\INST1'
-- Add the correct server as a local server
EXEC sp_addserver @.server='SUBSCRIBER1\INST1', @.local='local'
Reference:
PRB: Replication setup is not successful when SQL Server 2000 is - ID:
818334
http://support.microsoft.com/?id=818334
Fany Vargas
Microsoft Corporation
This posting is provided "AS IS" with no warranties, and confers no rights.
|||Hi Fany,
These are the following steps I have performed for changing the values srvid
to zero on subscriber
use master
sp_configure 'allow updates', 1 RECONFIGURE WITH OVERRIDE
update sysservers set srvid = 0 where srvname='subscriber_name'
sp_configure 'allow updates', 0
RECONFIGURE
It worked fine , and I am able to use merge replication properly now , pls
tell me if this way is correct if I face the same problem again ?
Regards,
Swati
"Fany Vargas [MSFT]" <fanyv@.online.microsoft.com> wrote in message
news:8DyA6M44EHA.3696@.cpmsftngxa10.phx.gbl...
> I want to confirm that what you mean is that on the subscriber you do not
> see a SRVID of 0 for the subscriber server when running sp_helpserver on
> the subscriber. So for example if my subscriber server is called
> SUBSCRIBER1\INST1, and sp_helpserver on this subscriber shows:
> name id
> -- --
> SUBSCRIBER1\INST1 0
> nameofpublisherserver 1
> then there is no problem, however if you see something like:
> name id
> -- --
> SUBSCRIBER1\INST1 2
> nameofpublisherserver 1
> then there is a problem because you should have server ID 0 for the local
> server. If that is the case you run the following to correctly set the
> local server name :
> -- Drop the server with incorrect name
> EXEC sp_dropserver @.server='SUBSCRIBER1\INST1'
> -- Add the correct server as a local server
> EXEC sp_addserver @.server='SUBSCRIBER1\INST1', @.local='local'
> Reference:
> PRB: Replication setup is not successful when SQL Server 2000 is - ID:
> 818334
> http://support.microsoft.com/?id=818334
>
> Fany Vargas
> Microsoft Corporation
> This posting is provided "AS IS" with no warranties, and confers no
rights.
>
|||This is the 'standard' way to reset the name in
sysservers:
Use Master
go
Sp_DropServer 'OldName'
GO
Use Master
go
Sp_Addserver 'NewName', 'local'
GO
Stop and Start SQL Services
HTH,
Paul Ibison SQL Server MVP, www.replicationanswers.com
(recommended sql server 2000 replication book:
http://www.nwsu.com/0974973602p.html)
|||You should stay away from directly modifying the system stored procedures.
Is there a particular reason why you could not run sp_dropserver +
sp_addserver (execute permissions?)?
a restart of the SQL Server service is necessary.
Fany Vargas
Microsoft Corporation
This posting is provided "AS IS" with no warranties, and confers no rights.
Are you secure? For information about the Strategic Technology Protection
Program and to order your FREE Security Tool Kit, please visit
http://www.microsoft.com/security.
Microsoft highly recommends that users with Internet access update their
Microsoft software to better protect against viruses and security
vulnerabilities. The easiest way to do this is to visit the following
websites:
http://www.microsoft.com/protect
http://www.microsoft.com/security/guidance/default.mspx
|||I made a typo I meant you should stay away from directly modifying system
tables. Especially if there is an interface provided to do the same (in
this case sp_dropserver,sp_addserver)
Fany Vargas
Microsoft Corporation
This posting is provided "AS IS" with no warranties, and confers no rights.
|||I will tk care hence forth , I was doing this exercise on test database
..Thanks for your help.
Regards
Swati
"Fany Vargas [MSFT]" <fanyv@.online.microsoft.com> wrote in message
news:K99KRPs5EHA.2600@.cpmsftngxa10.phx.gbl...
> I made a typo I meant you should stay away from directly modifying system
> tables. Especially if there is an interface provided to do the same (in
> this case sp_dropserver,sp_addserver)
> Fany Vargas
> Microsoft Corporation
> This posting is provided "AS IS" with no warranties, and confers no
rights.
>

Tuesday, February 14, 2012

Calculating RFM

I'm in the process of developing a Kimball-method CRM data warehouse and I'd like to have Recency, Frequency, Monetary "scores" at the customer level. Am I better off creating these in the relational database and feeding them to SSAS or have SSAS do the aggregations and assign the "scores"?

Also, has anyone located any SSIS transform scripts that would calculated RFM scores? This is probably a pretty easy task in VB.net but I haven't gone down that road yet.

Steve

Not strictly a Data Mining question, but here goes ...

How often do you want to calculate a score. Typically the Frequency and Monetary scores are only calculated monthly, quarterly or annually rather than being continuously updated. In this case, you would not really want to implement them as OLAP calculations, as the conditional logic in the calculation may get complicated.

You may well be better calculating these in a scheduled job in your ETL process, inserting them as facts, and having the OLAP cube roll them up as appropriate. I don't have SSIS scripts to calculate RFM, but as you say, a reasonably easy task.

BTW, here are some interesting articles on RFM that you may find useful too ...

A 3-part detailed guide ...

http://www.clickz.com/showPage.html?page=961901

http://www.clickz.com/showPage.html?page=971591

http://www.clickz.com/showPage.html?page=983891

A short piece on the theory ...

http://www.dbmarketing.com/articles/Art245.htm