Showing posts with label following. Show all posts
Showing posts with label following. Show all posts

Thursday, March 29, 2012

Executing SSIS from stored procedure - need to get return value into ASP.NET

I'm executing an SSIS package using the following stored procedure

ALTER PROC [dbo].[SSISRunBuildSCCDW]ASBEGINDECLARE @.ServerNameVARCHAR(30), @.ReturnValueint, @.Cmdvarchar(1000)SET @.ReturnValue = -1SET @.ServerName ='myserver'SET @.Cmd ='DTExec /SER ' + @.ServerName +' ' +' /SQL ' +'\BuildSCCDW '--Location of the package stored in the mdb --' /CONF "\\ConfigFilePath.dtsConfig" ' +--' /SET \Package.Variables[ImportUserID].Value; ' +--' /U "LoginName" /P "password" 'EXECUTE @.ReturnValue = master..xp_cmdshell @.Cmd, NO_OUTPUTRETURN @.ReturnValue--SELECT @.ReturnValue [Result]END

I'm then using a tableadapter to execute this from my ASP.NET page using the following code,

Protected Sub ExecutePackage()Dim ExecuteAdapterAs New SCC_DAL.RunSSISTableAdapters.SSISRunBuildSCCDWTableAdapter() ExecuteAdapter.SetCommandTimeOut(0)Dim strResultAs String strResult = ExecuteAdapter.Execute() lblResult.Text = strResultEnd Sub

If I remove 'NO_OUTPUT' from my stored procedure and run it the results contain a field named 'output' with all the steps from my package. Then below this is my return value. In my code I can only return the first step of the package results - which tells me nothing useful. I need to be able to return the return value (0-6) in my code.

When I have 'NO_OUTPUT' in my stored procedure and execute it I am left with just the return value. However no value is returned in my code at all although the package does run. I've tried bother RETURN @.ReturnValue and SELECT @.ReturnValue to no avail.

Can someone suggest how I can get the value 0-6 to my code?

Sorted!

Commented out RETURN @.ReturnValue and uncommented the line below it and it works. I had already tried that... bizarre.

Executing sql statements

When i execute the following in Sql query anlyzer

Declare @.dbname varchar(30),
@.str varchar(500),
@.emailID varchar(50)

set @.EmailID='santosh@.yahoo.com'

set @.dbname='DB_kms_prv'

set @.str='SELECT empid, NTName, officialEmail, PreferredName FROM ' +
@.dbname + '.dbo.tblEmployee where officialEmail=' + @.emailID

exec (@.str)

I get error message

The column prefix 'santosh@.yahoo' does not match with a table name or
alias name used in the query.
How to get rid of it..?You need to put single quotes around the address:

set @.str='SELECT empid, NTName, officialEmail, PreferredName FROM ' +
@.dbname + '.dbo.tblEmployee where officialEmail=''' + @.emailID + ''''

If you get syntax errors from dynamic SQL, then just 'SELECT @.sql'
before executing it, so you can see what the statement looks like -
that makes the problem much clearer.

But don't use dynamic SQL at all unless it's absolutely necessary - see
here for all the reasons why to avoid it, and alternative solutions:

http://www.sommarskog.se/dynamic_sql.html

Specifically for your case, see "Getting data from another database" in
this section:

http://www.sommarskog.se/dynamic_sql.html#Dyn_Db

Simonsql

Tuesday, March 27, 2012

Executing package from C# on 64bit platform

Hi

I have been successfully executing a series of IS packages from C# using the following syntax

Microsoft.SqlServer.Dts.Runtime.Package package;
package = app.LoadPackage(ISPackagePath + @."\myPackage.dtsx", null);
package.ImportConfigurationFile(ISPackagePath + @."\MyConfiguration.dtsConfig");
result = package.Execute();
package.Dispose();

My client has just moved their SQL boxes to a 64bit platform and this process no longer runs.

Now im also running some packages in a SQL Agent job on the SQL box and im aware of the issue of an SSIS job step defaulting to using the 64bit version of DTExec.exe. Ive updated those job steps to be operating system (cmdExec) type steps calling the 32bit version of DTExec.exe, and everything is fine there.

Is there anyway to force the Microsoft.SqlServer.Dts.Runtime.Package object in my C# code to use the 32bit version of DTEexec.exe? This code is running on the same 64bit SQL server box as the SQL agent job. Or will Microsoft.SqlServer.Dts.Runtime.Package object always default to using the 64 bit version if it is executed on a 64bit box ?

I would just call sp_start_job from C# and implement the IS packages in another job but unfortunatly my code cannot be given correct permissions to see the SQL agent jobs.

Any ideas?
Thanks

In a mixed platform environment you have to compile your code with AnyCPU instead of 32bits so just open your solutions in VS2005 and rebuild your code with AnyCPU and it will run in 64bits box. There maybe some configuration relevant to SSIS but in most mixed platform build with AnyCPU should fix it. I develop C# .NET applications with Oracle 9i/10g both 64bits with AnyCPU without any problems. Hope this helps.

|||

Caddre wrote:

I want to know about the performance using oracle packages in c#.net

Bhavin.

Bhavin_82@.hotmail.com

sql

Executing package from C#

Hi

I have been successfully executing a series of IS packages from C# using the following syntax

Microsoft.SqlServer.Dts.Runtime.Package package;
package = app.LoadPackage(ISPackagePath + @."\myPackage.dtsx", null);
package.ImportConfigurationFile(ISPackagePath + @."\MyConfiguration.dtsConfig");
result = package.Execute();
package.Dispose();

My client has just moved their SQL boxes to a 64bit platform and this process no longer runs.

Now im also running some packages in a SQL Agent job on the SQL box and im aware of the issue of an SSIS job step defaulting to using the 64bit version of DTExec.exe. Ive updated those job steps to be operating system (cmdExec) type steps calling the 32bit version of DTExec.exe, and everything is fine there.

Is there anyway to force the Microsoft.SqlServer.Dts.Runtime.Package object in my C# code to use the 32bit version of DTEexec.exe? This code is running on the same 64bit SQL server box as the SQL agent job. Or will Microsoft.SqlServer.Dts.Runtime.Package object always default to using the 64 bit version if it is executed on a 64bit box ?

I would just call sp_start_job from C# and implement the IS packages in another job but unfortunatly my code cannot be given correct permissions to see the SQL agent jobs.

Any ideas?
Thanks

In a mixed platform environment you have to compile your code with AnyCPU instead of 32bits so just open your solutions in VS2005 and rebuild your code with AnyCPU and it will run in 64bits box. There maybe some configuration relevant to SSIS but in most mixed platform build with AnyCPU should fix it. I develop C# .NET applications with Oracle 9i/10g both 64bits with AnyCPU without any problems. Hope this helps.

|||

Caddre wrote:

I want to know about the performance using oracle packages in c#.net

Bhavin.

Bhavin_82@.hotmail.com

executing multiple query at one time

hi,

i am making a n application which in between deletes the multiple tables from the sql database.

for that i have written the following code:

SqlCommand cmd = newSqlCommand();

cmd.CommandText = "delete from " + dbConstt.DBSchema + ".PicassoSelectivityLog where QTID=" + qtid;

cmd.ExecuteNonQuery();

cmd.CommandText = "delete from " + dbConstt.DBSchema + ".PicassoSelectivityLog where QTID=" + qtid;

cmd.ExecuteNonQuery();

in this way, many more tables are to be deleted.

is there any need to create the new SQLCommand object again an\d agin for each and every query. can iot be done like the given above or can there be some better method?

thanz in advance..

divya

What about creating a static method, passing in the connection and the things that can change in the query, composing query query within the method and executing this thing asynchronously ?

HTH, Jens K. Suessmeyer.

http://www.sqlserver2005.de
sql

Monday, March 26, 2012

Executing DTS packages in 64 bit SSIS

Hello Everyone,

I am going through the following article

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

and I have some clarifications to seek.

Based on the above article it seems its possible to run a DTS package on a SQL 2006 X64 machine.

Furthermore it seems possible that this package will run without any upgrade being performed to SSIS.

Also, to execute the DTS package in 32 bit mode, all I have to do is to set the job step type of SQL Agent to Operating system, and enter a command line or use a batch file that invokes the 32-bit version of dtexec.exe. You can use the dtexecui.exe utility to create the command line, and then copy and paste the command line into the job step.

Are the above deductions correct? Please let me know if some correction / refinement is needed.

There is no 64-bit design-time or run-time support for DTS packages.

You can run DTS packages (SQL Server 2000), as well as SSIS packages (SQL Server 2005), on the same 32-bit machine. You can use the dtsrun.exe utility to run the DTS packages from the command prompt. You also have the option of running a DTS package from a SSIS package (SQL Server 2005) by adding the Execute DTS 2000 Package task to the SSIS package.

For more information about SQL Server 2005 support for DTS packages, see "SQL Server 2005 Integration Services Backward Compatibility" at http://msdn2.microsoft.com/en-us/library/ms143706.aspx#runtime_installing.

Executing a unit of work without replication

We are using SQL Server 2000 on Win2003.
I would like to do something like the following on a replicated system.
BEGIN WORK WITHOUT REPLICATION;
...
<Some insert, update or delete SQL>
...
COMMIT;
Is there any way to achieve this non-replicated transaction with SQL
Server. This needs to be an on-line activity in parallel with other
replicated transactions.
Thanks,
Redden96
if there is something about the nature of the update you can
encapsulate logic into your replication stored procedures to skip these
transactions. For instance if you have a column which has a unique
value for this type of work you do not want replicated you could trap
for this value in the replication stored procedures.
Another option is to put filters on your articles which look like this
select * from publishedtables where 1=1
Then in your filter procs change them to always return 0 when you want
these transactions skipped. When you want replication to pick up
transactions again, change it to 1.
|||Thanks Hilary. I was hoping for something a little less invasive, but I
can make a solution similar to the one you describe work for me.

Friday, March 23, 2012

Executing a SSIS Package from an ASP.NET page.

I am using the following code to try and execute a package from a asp.net page. The server has both SQL, SSIS, IIS and ASP.NET on it. The package runs fine from the SQL Management Studio. The Execute result from the web page is 'Failure'.

My questions are:
1. How do I catch errors to see exactly what is failing and why?
2. Is there a better way to execute a package using SSIS from asp.net?

Thanks,

Nathan

Sub ExecutePackage()
Dim pkg As New Package
Dim app As New Application
Dim pkgResults As DTSExecResult

Dim testBool As Boolean = app.ExistsOnSqlServer("\\Import_Quotes", "povnet", "webapps", "password")
lblStatus.Text = testBool.ToString
pkg = app.LoadFromSqlServer("\\Import_Quotes", "povnet", "webapps", "password", Nothing)
pkgResults = pkg.Execute()

lblErrorOther.Text = pkgResults.ToString()
End Sub

> How do I catch errors to see exactly what is failing and why?

There are multiple ways:
1) Enable logging and configure package to log execution and error information to a file, event log or other log provider. This gives you a lot of information about package.
2) Implement IDtsEvents interface and supply it to Execute method. You'll get lots of information (in particular, all the error information) back.

The code seems fine.

By the way, the common problem with executing SSIS package from ASP.NET is user identify - the package is executed under account used by ASP.NET service, which might not have permissions to access all the data sources.|||Michael,

Can you help me with some code samples of implementing IDtsEvents and using it in the Execute method?

Also, I will check BOL but any info you can provide on enabling logging on a package would be nice.

Thanks for your quick response.

Nathan|||Implementing IDtsEvents is simple - subclass from Microsoft.SqlServer.Dts.Runtime.DefaultEvents class and override the methods corresponding to events you are interested in, most probably OnError. Pass instance of your class to Execute call, your OnError method will be called whenever an error occurs during execution.

To enable logging, right click the package main control flow in designer, select Package Configurations and follow the wizard.

Note - to edit configuration the package should be part of SSIS project, this currently does not work for packages edited "standalone" (unfortunately, this problem was found too late). I'm fixing it for SP1.|||

Here are some of the errors. I believe it is a permissions problem. I am importing an Excel spreadsheet to the database. The spreadsheet exists on the same server as the database. I have given NTFS permissions to NETWORK SERVICE to access the file. What other types of permissions do I need to grant the NETWORK SERVICE account?

Event Type: Error
Event Source: SQLISPackage
Event Category: None
Event ID: 12550
Date: 10/28/2005
Time: 1:08:31 PM
User: NT AUTHORITY\NETWORK SERVICE
Computer: POVNET
Description:
Event Name: OnError
Message: The AcquireConnection method call to the connection manager "POVNET SQL Database" failed with error code 0xC0202009.

Operator: NT AUTHORITY\NETWORK SERVICE
Source Name: Import Quote Pricing
Source ID: {55F39A44-4089-4C2E-9267-33332166020D}
Execution ID: {68483D6C-895B-450A-ABA5-9E50E333D4C9}
Start Time: 10/28/2005 1:08:31 PM
End Time: 10/28/2005 1:08:31 PM
Data Code: -1071611876

For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.

AND

Event Type: Error
Event Source: SQLISPackage
Event Category: None
Event ID: 12550
Date: 10/28/2005
Time: 1:08:31 PM
User: NT AUTHORITY\NETWORK SERVICE
Computer: POVNET
Description:
Event Name: OnError
Message: component "SQL Server Destination" (953) failed validation and returned error code 0xC020801C.

Operator: NT AUTHORITY\NETWORK SERVICE
Source Name: Import Quote Pricing
Source ID: {55F39A44-4089-4C2E-9267-33332166020D}
Execution ID: {68483D6C-895B-450A-ABA5-9E50E333D4C9}
Start Time: 10/28/2005 1:08:31 PM
End Time: 10/28/2005 1:08:31 PM
Data Code: -1073450985

For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.

|||The message
Message: component "SQL Server Destination" (953) failed validation and returned error code 0xC020801C.
indicates an error with SQL Server destination, not the Excel spreadsheet.

Also see the error the connection manager "POVNET SQL Database" - well, only you know where this connection manager points to.|||When I am in SQL Management Studio and run the Package, it runs without errors. I understand that the error is realted to the SQL Destination. When I execute this command from ASP.NET, which username is used for the operation?

Thanks,
Nathan|||

Do you use integrated NT authentication for SQL Destination? Then account ASP.NET is running under, usually Network Service (it authenticates as Domain\Computer$ to remote servers).

|||I can get my package to execute successfully now using ASP.NET.

Can you help me out on implementing IDTSEvents using asp.net and vb.net? I know you mentioned that it is simple, however, I am a beginner and am not sure how to tackle it.

I am looking to collect information on the results of the package like success or failure and also other things like varibles from the package like row count etc.

Thanks for your help on this.

Nathan|||

Microsoft.SqlServer.ManagedDTS assembly has a class DefaultEvents (in namespace Microsoft.SqlServer.Dts.Runtime). You just subclass this type and override the methods corresponding to the events you are interested in (e.g. OnError).

Then you pass an instance of your class to package.Execute method, like
package.Execute(null, null, myEvents, null);

|||Michael,
As you know, the word 'simple' is totally relative to a persons knowledge base. In my case at least, it is very limited in the program development arena so could you please direct me to documentation or an example of how to implement the event handler that you mentioned?

Thanks,
Mark.

Executing a SSIS Package from an ASP.NET page.

I am using the following code to try and execute a package from a asp.net page. The server has both SQL, SSIS, IIS and ASP.NET on it. The package runs fine from the SQL Management Studio. The Execute result from the web page is 'Failure'.

My questions are:
1. How do I catch errors to see exactly what is failing and why?
2. Is there a better way to execute a package using SSIS from asp.net?

Thanks,

Nathan

Sub ExecutePackage()
Dim pkg As New Package
Dim app As New Application
Dim pkgResults As DTSExecResult

Dim testBool As Boolean = app.ExistsOnSqlServer("\\Import_Quotes", "povnet", "webapps", "password")
lblStatus.Text = testBool.ToString
pkg = app.LoadFromSqlServer("\\Import_Quotes", "povnet", "webapps", "password", Nothing)
pkgResults = pkg.Execute()

lblErrorOther.Text = pkgResults.ToString()
End Sub

> How do I catch errors to see exactly what is failing and why?

There are multiple ways:
1) Enable logging and configure package to log execution and error information to a file, event log or other log provider. This gives you a lot of information about package.
2) Implement IDtsEvents interface and supply it to Execute method. You'll get lots of information (in particular, all the error information) back.

The code seems fine.

By the way, the common problem with executing SSIS package from ASP.NET is user identify - the package is executed under account used by ASP.NET service, which might not have permissions to access all the data sources.|||Michael,

Can you help me with some code samples of implementing IDtsEvents and using it in the Execute method?

Also, I will check BOL but any info you can provide on enabling logging on a package would be nice.

Thanks for your quick response.

Nathan|||Implementing IDtsEvents is simple - subclass from Microsoft.SqlServer.Dts.Runtime.DefaultEvents class and override the methods corresponding to events you are interested in, most probably OnError. Pass instance of your class to Execute call, your OnError method will be called whenever an error occurs during execution.

To enable logging, right click the package main control flow in designer, select Package Configurations and follow the wizard.

Note - to edit configuration the package should be part of SSIS project, this currently does not work for packages edited "standalone" (unfortunately, this problem was found too late). I'm fixing it for SP1.|||

Here are some of the errors. I believe it is a permissions problem. I am importing an Excel spreadsheet to the database. The spreadsheet exists on the same server as the database. I have given NTFS permissions to NETWORK SERVICE to access the file. What other types of permissions do I need to grant the NETWORK SERVICE account?

Event Type: Error
Event Source: SQLISPackage
Event Category: None
Event ID: 12550
Date: 10/28/2005
Time: 1:08:31 PM
User: NT AUTHORITY\NETWORK SERVICE
Computer: POVNET
Description:
Event Name: OnError
Message: The AcquireConnection method call to the connection manager "POVNET SQL Database" failed with error code 0xC0202009.

Operator: NT AUTHORITY\NETWORK SERVICE
Source Name: Import Quote Pricing
Source ID: {55F39A44-4089-4C2E-9267-33332166020D}
Execution ID: {68483D6C-895B-450A-ABA5-9E50E333D4C9}
Start Time: 10/28/2005 1:08:31 PM
End Time: 10/28/2005 1:08:31 PM
Data Code: -1071611876

For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.

AND

Event Type: Error
Event Source: SQLISPackage
Event Category: None
Event ID: 12550
Date: 10/28/2005
Time: 1:08:31 PM
User: NT AUTHORITY\NETWORK SERVICE
Computer: POVNET
Description:
Event Name: OnError
Message: component "SQL Server Destination" (953) failed validation and returned error code 0xC020801C.

Operator: NT AUTHORITY\NETWORK SERVICE
Source Name: Import Quote Pricing
Source ID: {55F39A44-4089-4C2E-9267-33332166020D}
Execution ID: {68483D6C-895B-450A-ABA5-9E50E333D4C9}
Start Time: 10/28/2005 1:08:31 PM
End Time: 10/28/2005 1:08:31 PM
Data Code: -1073450985

For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.

|||The message
Message: component "SQL Server Destination" (953) failed validation and returned error code 0xC020801C.
indicates an error with SQL Server destination, not the Excel spreadsheet.

Also see the error the connection manager "POVNET SQL Database" - well, only you know where this connection manager points to.|||When I am in SQL Management Studio and run the Package, it runs without errors. I understand that the error is realted to the SQL Destination. When I execute this command from ASP.NET, which username is used for the operation?

Thanks,
Nathan|||

Do you use integrated NT authentication for SQL Destination? Then account ASP.NET is running under, usually Network Service (it authenticates as Domain\Computer$ to remote servers).

|||I can get my package to execute successfully now using ASP.NET.

Can you help me out on implementing IDTSEvents using asp.net and vb.net? I know you mentioned that it is simple, however, I am a beginner and am not sure how to tackle it.

I am looking to collect information on the results of the package like success or failure and also other things like varibles from the package like row count etc.

Thanks for your help on this.

Nathan|||

Microsoft.SqlServer.ManagedDTS assembly has a class DefaultEvents (in namespace Microsoft.SqlServer.Dts.Runtime). You just subclass this type and override the methods corresponding to the events you are interested in (e.g. OnError).

Then you pass an instance of your class to package.Execute method, like
package.Execute(null, null, myEvents, null);

|||Michael,
As you know, the word 'simple' is totally relative to a persons knowledge base. In my case at least, it is very limited in the program development arena so could you please direct me to documentation or an example of how to implement the event handler that you mentioned?

Thanks,
Mark.

Executing a SSIS Package from an ASP.NET page.

I am using the following code to try and execute a package from a asp.net page. The server has both SQL, SSIS, IIS and ASP.NET on it. The package runs fine from the SQL Management Studio. The Execute result from the web page is 'Failure'.

My questions are:
1. How do I catch errors to see exactly what is failing and why?
2. Is there a better way to execute a package using SSIS from asp.net?

Thanks,

Nathan

Sub ExecutePackage()
Dim pkg As New Package
Dim app As New Application
Dim pkgResults As DTSExecResult

Dim testBool As Boolean = app.ExistsOnSqlServer("\\Import_Quotes", "povnet", "webapps", "password")
lblStatus.Text = testBool.ToString
pkg = app.LoadFromSqlServer("\\Import_Quotes", "povnet", "webapps", "password", Nothing)
pkgResults = pkg.Execute()

lblErrorOther.Text = pkgResults.ToString()
End Sub

> How do I catch errors to see exactly what is failing and why?

There are multiple ways:
1) Enable logging and configure package to log execution and error information to a file, event log or other log provider. This gives you a lot of information about package.
2) Implement IDtsEvents interface and supply it to Execute method. You'll get lots of information (in particular, all the error information) back.

The code seems fine.

By the way, the common problem with executing SSIS package from ASP.NET is user identify - the package is executed under account used by ASP.NET service, which might not have permissions to access all the data sources.|||Michael,

Can you help me with some code samples of implementing IDtsEvents and using it in the Execute method?

Also, I will check BOL but any info you can provide on enabling logging on a package would be nice.

Thanks for your quick response.

Nathan|||Implementing IDtsEvents is simple - subclass from Microsoft.SqlServer.Dts.Runtime.DefaultEvents class and override the methods corresponding to events you are interested in, most probably OnError. Pass instance of your class to Execute call, your OnError method will be called whenever an error occurs during execution.

To enable logging, right click the package main control flow in designer, select Package Configurations and follow the wizard.

Note - to edit configuration the package should be part of SSIS project, this currently does not work for packages edited "standalone" (unfortunately, this problem was found too late). I'm fixing it for SP1.|||

Here are some of the errors. I believe it is a permissions problem. I am importing an Excel spreadsheet to the database. The spreadsheet exists on the same server as the database. I have given NTFS permissions to NETWORK SERVICE to access the file. What other types of permissions do I need to grant the NETWORK SERVICE account?

Event Type: Error
Event Source: SQLISPackage
Event Category: None
Event ID: 12550
Date: 10/28/2005
Time: 1:08:31 PM
User: NT AUTHORITY\NETWORK SERVICE
Computer: POVNET
Description:
Event Name: OnError
Message: The AcquireConnection method call to the connection manager "POVNET SQL Database" failed with error code 0xC0202009.

Operator: NT AUTHORITY\NETWORK SERVICE
Source Name: Import Quote Pricing
Source ID: {55F39A44-4089-4C2E-9267-33332166020D}
Execution ID: {68483D6C-895B-450A-ABA5-9E50E333D4C9}
Start Time: 10/28/2005 1:08:31 PM
End Time: 10/28/2005 1:08:31 PM
Data Code: -1071611876

For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.

AND

Event Type: Error
Event Source: SQLISPackage
Event Category: None
Event ID: 12550
Date: 10/28/2005
Time: 1:08:31 PM
User: NT AUTHORITY\NETWORK SERVICE
Computer: POVNET
Description:
Event Name: OnError
Message: component "SQL Server Destination" (953) failed validation and returned error code 0xC020801C.

Operator: NT AUTHORITY\NETWORK SERVICE
Source Name: Import Quote Pricing
Source ID: {55F39A44-4089-4C2E-9267-33332166020D}
Execution ID: {68483D6C-895B-450A-ABA5-9E50E333D4C9}
Start Time: 10/28/2005 1:08:31 PM
End Time: 10/28/2005 1:08:31 PM
Data Code: -1073450985

For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.|||The message
Message: component "SQL Server Destination" (953) failed validation and returned error code 0xC020801C.
indicates an error with SQL Server destination, not the Excel spreadsheet.

Also see the error the connection manager "POVNET SQL Database" - well, only you know where this connection manager points to.|||When I am in SQL Management Studio and run the Package, it runs without errors. I understand that the error is realted to the SQL Destination. When I execute this command from ASP.NET, which username is used for the operation?

Thanks,
Nathan|||

Do you use integrated NT authentication for SQL Destination? Then account ASP.NET is running under, usually Network Service (it authenticates as Domain\Computer$ to remote servers).

|||I can get my package to execute successfully now using ASP.NET.

Can you help me out on implementing IDTSEvents using asp.net and vb.net? I know you mentioned that it is simple, however, I am a beginner and am not sure how to tackle it.

I am looking to collect information on the results of the package like success or failure and also other things like varibles from the package like row count etc.

Thanks for your help on this.

Nathan|||

Microsoft.SqlServer.ManagedDTS assembly has a class DefaultEvents (in namespace Microsoft.SqlServer.Dts.Runtime). You just subclass this type and override the methods corresponding to the events you are interested in (e.g. OnError).

Then you pass an instance of your class to package.Execute method, like
package.Execute(null, null, myEvents, null);

|||Michael,
As you know, the word 'simple' is totally relative to a persons knowledge base. In my case at least, it is very limited in the program development arena so could you please direct me to documentation or an example of how to implement the event handler that you mentioned?

Thanks,
Mark.

executing a package with dtexec.exe

Hi,
when I run the following from the command prompt I am getting an error saying that can not set the variable Status as int.

dtexec /File "C:\work\SSIS Packages\Dataflow\ControlRoom.dtsx" /SET

\Package.Variables[ChannelCode].Value;"test" /SET

\Package.Variables[Status].Value;1

both variables as you can see are in the top level.
the problem is that ChannelCode is string but Status is Integer.
if I take out the /SET \Package.Variables[Status].Value;1 part from the command line it will work fine. I think th eproblem is down to diffenrt types of variable as there are two types of String and Interger.

any ideas on what the problem migth be.
p.s. I am runnning SQL server 2005 Dev edition (without any SP)
CheersAre you sure [Status] is an integer in your package?

What happens when you run it with:
/SET \Package.Variables[Status].Value;"1"|||yes it is Integer and don't want to change it to string as I have ament that in few places in my package|||Have you tried DTexecUI to set those values and see how the command line gets generated?|||this is what get's generated

/FILE "C:\work\SSIS Packages\Dataflow\ControlRoom.dtsx" /MAXCONCURRENT " -1 " /CHECKPOINTING OFF /REPORTING EW /SET "\Package.Variables[ChannelCode].Value";Test /SET "\Package.Variables[Status].Value";1
but I'm getting the same problem
back to square one|||Can you please post the exact error?|||I'm getting

Started: 4:56:31 PM
Error: 2007-03-26 16:56:33.37
Code: 0xC0017006
Source: ControlRoom
Description: The expression "@.Status == 1" must evaluate to True or False. Ch
ange the expression to evaluate to a Boolean value.
End Error
Error: 2007-03-26 16:56:33.37
Code: 0xC0014021
Source: ControlRoom

as it does a check against the Status value that I'm loading from the command prompt.
if I specify (hardcode) the variable value inside the package it will work fine, this happens only when I try to pass the value from command prompt
Thanks|||Do you have EvaluateAsExpression set to false when you need to have it set to true somewhere?

I don't think we have all of the pieces of the puzzle here, but it seems that "@.Status == 1" is being passed in as a string, not a conditional check.|||sorry, I think it's my fault as I didn't plain a clear picture.
I am passing the variable Status from command prompt and inside the package it trys to check if the passes value is 1
as the Status value is not getting passed from the command prompt and the default value of @.Status in the package is to 0, the condition fails.

now if I hardcode the default value of @.status in the package to 1 and do not try to pass the value for status from command prompt. it work perfectly!
I hope this makes it clear|||And the scope of the variable is correct? You don't have two variables of the same name in different scopes, do you? This can happen.

For instance, you could have a Status variable of package scope and have a Status variable of data flow scope in the same package.|||I thought that this might be the issue but I'm looking at all the variables across the whole package and there isn't any other one with the same name. @.Status is the only and as you can see it is at the top level so it is visible by all the sub tasks.
cheers|||

Kolf wrote:

I thought that this might be the issue but I'm looking at all the variables across the whole package and there isn't any other one with the same name. @.Status is the only and as you can see it is at the top level so it is visible by all the sub tasks.
cheers

Yep, I can see that, but just because it's visible to subtasks doesn't mean that the subtasks can't have their own variable of the same name, that's why I asked.|||

Kolf wrote:

... and inside the package it trys to check if the passes value is 1 ...

How are you doing this? Where are you doing this? Control flow, data flow, conditional split, derived column, etc...|||in the varaible windows I click on a button called show user variable and that displays all the variables define with in that package and I have just one variable called @.Status which is Int32
Thanks

Executing a package from within a C# program returns failure everytime

Hi All,

I am trying to execute a package (programmatically) that is stored on my local disk using the information that is provided on the following page:

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

This means, I am using the Application object and the Package object to actually load the package using the path to it.

So my code looks something like this:

--

pkgLocation = @."<package_path>/Package1.dtsx";

app = new Application();

pkg = app.LoadPackage(pkgLocation, null);

pkgResults = pkg.Execute();

Console.WriteLine(pkgResults.ToString());

Console.ReadKey();

My package reads in a flat file (located on another server) and transforms it and saves it to a database (on that same server). And mind you, I can execute this package just fine when I do it manually from within BIDS.

But when I try to execute the above mentioned code in my C# solution (compiled to a command line executable), I always get a "Failure".

Can somebody point out what I am doing wrong here?

Thank you in advance,

Manan Pancholi

You can use the following code to get the errors after execution

foreach (DtsError dtserr in pkg.Errors)
{
Console.WriteLine("Source: " + dtserr.Source + ", Description: " + dtserr.Description);
}|||

Thanks Kaarthik,

I believe I have narrowed down the problem. It seems that unless the Integration Services are installed on my machine, I would not be able to execute some tasks that are part of the package that I am calling programmatically. Atleast thats what the error information pointed out to me.

I believe that the authentication works differently when I am trying to execute the package manually and when I am trying to execute the package in my C# code. This is kind of odd, but thanks again for the help.

I will follow this up with a detailed example of how to execute a package programmatically and what sort of permissions would one need when working with remote sources and destinations.

Manan Pancholi

Wednesday, March 21, 2012

executeUpdate return 0 rowcount for an update

Hi! I have a developer who reported the following problem
"For those of you who aren't familiar, the way we modify data in the Java
apps is through an API called JDBC. The JDBC API provides a
PreparedStatement class that allows you to assemble sql and then have it
executed. In the case of an update statement, you are supposed to call an
executeUpdate method. That method is supposed to return the number of rows
updated by the command. If it returns 0, I was assuming that no rows were
updated, hence the locking failure. I finally decided that maybe the row was
getting updated, but executeUpdate was incorrectly returning 0. I just
tested that theory and found it to be the case. The row is updated, but
executeUpdate is returning 0."
The query statement passed to executeUpdate is a simple update statement
(update ... set .. where ..)
The table developer tried to update has an update trigger which has executed
2 INSERT statements:
INSERT statement #1 adds records into transaction_touch table and
INSERT statement #2 adds records into an audit table
The transaction_touch table has an insert trigger which populates data into
another table. The test showed that
no record was added into this table. Therefore, the rowcount is 0. If I
commented out the INSERT statement inside
the transaction_touch insert trigger, a non-zero rrowcount was returned back
to Java apps.
I don't know if anybody has experienced this problem using MS JDBC driver to
access MS SQL Server 2000? If
you do and has a solution, please let me know. Thanks
-- Peter Lo
Peter:
We're going to investigate this one further and post back what we find.
Can you post the trigger repro code -- that would be helpful.
-shelby
Shelby Goerlitz
Microsoft, SQL Server
"Peter Lo" <peter.lo@.tradecapture.com> wrote in message
news:OLvobEkhFHA.3568@.TK2MSFTNGP10.phx.gbl...
> Hi! I have a developer who reported the following problem
> "For those of you who aren't familiar, the way we modify data in the Java
> apps is through an API called JDBC. The JDBC API provides a
> PreparedStatement class that allows you to assemble sql and then have it
> executed. In the case of an update statement, you are supposed to call an
> executeUpdate method. That method is supposed to return the number of rows
> updated by the command. If it returns 0, I was assuming that no rows were
> updated, hence the locking failure. I finally decided that maybe the row
> was
> getting updated, but executeUpdate was incorrectly returning 0. I just
> tested that theory and found it to be the case. The row is updated, but
> executeUpdate is returning 0."
> The query statement passed to executeUpdate is a simple update statement
> (update ... set .. where ..)
> The table developer tried to update has an update trigger which has
> executed
> 2 INSERT statements:
> INSERT statement #1 adds records into transaction_touch table and
> INSERT statement #2 adds records into an audit table
> The transaction_touch table has an insert trigger which populates data
> into
> another table. The test showed that
> no record was added into this table. Therefore, the rowcount is 0. If I
> commented out the INSERT statement inside
> the transaction_touch insert trigger, a non-zero rrowcount was returned
> back
> to Java apps.
> I don't know if anybody has experienced this problem using MS JDBC driver
> to
> access MS SQL Server 2000? If
> you do and has a solution, please let me know. Thanks
>
> -- Peter Lo
>
>
>
>
|||Shelby:
The update statement executed by Java apps looks like this:
update icts_user where user_init = '?' and trans_id = ?
==> In this example, only one icts_user record will be modified
Here are the triggers:
create trigger icts_user_updtrg
on icts_user
for update
as
declare @.num_rows int,
@.count_num_rows int,
@.errmsg varchar(255)
select @.num_rows = @.@.rowcount
if @.num_rows = 0
return
if update(loc_code)
begin
if exists (select 1 from inserted
where loc_code not in (select loc_code from location))
begin
if @.num_rows = 1
begin
select @.errmsg = 'The loc_code ''' + loc_code + ''' is not a valid
code defined in the location table.'
from inserted
end
else
begin
select @.errmsg = 'The loc_code is not a valid code defined in the
location table.'
end
raiserror 20002 @.errmsg
rollback tran
return
end
end
if exists (select 1 from inserted, icts_user
where icts_user.user_logon_id = rtrim(inserted.user_logon_id) and
icts_user.user_init != inserted.user_init)
begin
if @.num_rows = 1
begin
select @.errmsg = 'The new user_logon_id ''' + user_logon_id + ''' has
existed in the icts_user table. Duplicate is not allowed!'
from inserted
end
else
begin
select @.errmsg = 'The new user_logon_id(s) have existed in the
icts_user table. Duplicate is not allowed!'
end
raiserror 20003 @.errmsg
rollback tran
return
end
/* END_DATA_INTEGRITY */
if not update(trans_id)
begin
raiserror 20090 '(icts_user) The change needs to be attached with a new
trans_id'
rollback tran
return
end
if exists (select 1
from master.dbo.sysprocesses
where spid = @.@.spid and
rtrim(program_name) IN ('ISQL-32', 'OSQL-32', 'SQL Query
Analyzer') )
begin
if (select count(*) from inserted, deleted where inserted.trans_id <=
deleted.trans_id) > 0
begin
select @.errmsg = '(icts_user) New trans_id must be larger than
original trans_id.'
select @.errmsg = @.errmsg + char(10) + 'You can use the the
gen_new_transaction procedure to obtain a new trans_id.'
raiserror 20092 @.errmsg
rollback tran
return
end
end
if exists (select * from inserted i, deleted d
where i.trans_id < d.trans_id and
i.user_init = d.user_init )
begin
raiserror 20091 '(icts_user) new trans_id must not be older than current
trans_id.'
rollback tran
return
end
select @.dummy_update = 0
if update(user_init)
begin
select @.count_num_rows = (select count(*) from inserted i, deleted d
where i.user_init = d.user_init )
if (@.count_num_rows = @.num_rows)
begin
select @.dummy_update = 1
end
else
begin
raiserror 20072 '(icts_user) primary key can not be changed.'
rollback tran
return
end
end
insert transaction_touch
select 'UPDATE',
'IctsUser',
'DIRECT',
convert(varchar(40), i.user_init),
null,
null,
null,
null,
null,
null,
null,
i.trans_id,
it.sequence
from inserted i, icts_transaction it
where i.trans_id = it.trans_id and
it.type != 'E'
if @.dummy_update = 0
insert aud_icts_user
(user_init,
user_last_name,
user_first_name,
desk_code,
loc_code,
user_logon_id,
us_citizen_ind,
user_job_title,
user_status,
user_employee_num,
email_address,
defaults_information_id,
trans_id,
resp_trans_id)
select
d.user_init,
d.user_last_name,
d.user_first_name,
d.desk_code,
d.loc_code,
d.user_logon_id,
d.us_citizen_ind,
d.user_job_title,
d.user_status,
d.user_employee_num,
d.email_address,
d.defaults_information_id,
d.trans_id,
i.trans_id
from deleted d, inserted i
where d.user_init = i.user_init
return
go
/* ***************************** */
create trigger transaction_touch_instrg
on transaction_touch
for insert
as
declare @.num_rows int,
@.count_num_rows int,
@.errmsg varchar(255)
select @.num_rows = @.@.rowcount
if @.num_rows = 0
return
insert into als_run_touch
(als_module_group_id, operation, entity_name,key1,key2,
key3,key4,key5,key6,key7,key8,trans_id,sequence,to uch_key)
select a.als_module_group_id,
case when i.operation = 'INSERT' then 'I'
when i.operation = 'UPDATE' then 'U'
when i.operation = 'DELETE' then 'D'
end,
i.entity_name,
i.key1,
i.key2,
i.key3,
i.key4,
i.key5,
i.key6,
i.key7,
i.key8,
i.trans_id,
i.sequence,
i.touch_key
from als_module_entity a,
inserted i
where ( ( ((a.operation_type_mask & 1) = 1) and (i.operation =
'INSERT') ) OR
( ((a.operation_type_mask & 2) = 2) and (i.operation =
'UPDATE') ) OR
( ((a.operation_type_mask & 4) = 4) and (i.operation =
'DELETE') ) ) AND
(a.entity_name = i.entity_name)
return
go
The aud_icts_user table does not have triggers. I hope this help
-- Peter Lo
"Shelby Goerlitz [MSFT]" <shelbyg@.nospam.microsoft.com> wrote in message
news:uaP2%235whFHA.2180@.TK2MSFTNGP15.phx.gbl...[vbcol=seagreen]
> Peter:
> We're going to investigate this one further and post back what we find.
> Can you post the trigger repro code -- that would be helpful.
> -shelby
> Shelby Goerlitz
> Microsoft, SQL Server
>
> "Peter Lo" <peter.lo@.tradecapture.com> wrote in message
> news:OLvobEkhFHA.3568@.TK2MSFTNGP10.phx.gbl...
Java[vbcol=seagreen]
an[vbcol=seagreen]
rows[vbcol=seagreen]
were[vbcol=seagreen]
driver
>
|||Peter --
thx for the info -- that is very helpful. just to let you know, dev is
still looking at this issue.
-shelby
Shelby Goerlitz
Microsoft, SQL Server
"Peter Lo" <peter.lo@.tradecapture.com> wrote in message
news:OM5tnTyhFHA.3608@.TK2MSFTNGP12.phx.gbl...
> Shelby:
> The update statement executed by Java apps looks like this:
> update icts_user where user_init = '?' and trans_id = ?
> ==> In this example, only one icts_user record will be modified
> Here are the triggers:
> create trigger icts_user_updtrg
> on icts_user
> for update
> as
> declare @.num_rows int,
> @.count_num_rows int,
> @.errmsg varchar(255)
> select @.num_rows = @.@.rowcount
> if @.num_rows = 0
> return
> if update(loc_code)
> begin
> if exists (select 1 from inserted
> where loc_code not in (select loc_code from location))
> begin
> if @.num_rows = 1
> begin
> select @.errmsg = 'The loc_code ''' + loc_code + ''' is not a valid
> code defined in the location table.'
> from inserted
> end
> else
> begin
> select @.errmsg = 'The loc_code is not a valid code defined in the
> location table.'
> end
> raiserror 20002 @.errmsg
> rollback tran
> return
> end
> end
> if exists (select 1 from inserted, icts_user
> where icts_user.user_logon_id = rtrim(inserted.user_logon_id)
> and
> icts_user.user_init != inserted.user_init)
> begin
> if @.num_rows = 1
> begin
> select @.errmsg = 'The new user_logon_id ''' + user_logon_id + ''' has
> existed in the icts_user table. Duplicate is not allowed!'
> from inserted
> end
> else
> begin
> select @.errmsg = 'The new user_logon_id(s) have existed in the
> icts_user table. Duplicate is not allowed!'
> end
> raiserror 20003 @.errmsg
> rollback tran
> return
> end
> /* END_DATA_INTEGRITY */
> if not update(trans_id)
> begin
> raiserror 20090 '(icts_user) The change needs to be attached with a new
> trans_id'
> rollback tran
> return
> end
> if exists (select 1
> from master.dbo.sysprocesses
> where spid = @.@.spid and
> rtrim(program_name) IN ('ISQL-32', 'OSQL-32', 'SQL Query
> Analyzer') )
> begin
> if (select count(*) from inserted, deleted where inserted.trans_id <=
> deleted.trans_id) > 0
> begin
> select @.errmsg = '(icts_user) New trans_id must be larger than
> original trans_id.'
> select @.errmsg = @.errmsg + char(10) + 'You can use the the
> gen_new_transaction procedure to obtain a new trans_id.'
> raiserror 20092 @.errmsg
> rollback tran
> return
> end
> end
> if exists (select * from inserted i, deleted d
> where i.trans_id < d.trans_id and
> i.user_init = d.user_init )
> begin
> raiserror 20091 '(icts_user) new trans_id must not be older than current
> trans_id.'
> rollback tran
> return
> end
> select @.dummy_update = 0
> if update(user_init)
> begin
> select @.count_num_rows = (select count(*) from inserted i, deleted d
> where i.user_init = d.user_init )
> if (@.count_num_rows = @.num_rows)
> begin
> select @.dummy_update = 1
> end
> else
> begin
> raiserror 20072 '(icts_user) primary key can not be changed.'
> rollback tran
> return
> end
> end
> insert transaction_touch
> select 'UPDATE',
> 'IctsUser',
> 'DIRECT',
> convert(varchar(40), i.user_init),
> null,
> null,
> null,
> null,
> null,
> null,
> null,
> i.trans_id,
> it.sequence
> from inserted i, icts_transaction it
> where i.trans_id = it.trans_id and
> it.type != 'E'
> if @.dummy_update = 0
> insert aud_icts_user
> (user_init,
> user_last_name,
> user_first_name,
> desk_code,
> loc_code,
> user_logon_id,
> us_citizen_ind,
> user_job_title,
> user_status,
> user_employee_num,
> email_address,
> defaults_information_id,
> trans_id,
> resp_trans_id)
> select
> d.user_init,
> d.user_last_name,
> d.user_first_name,
> d.desk_code,
> d.loc_code,
> d.user_logon_id,
> d.us_citizen_ind,
> d.user_job_title,
> d.user_status,
> d.user_employee_num,
> d.email_address,
> d.defaults_information_id,
> d.trans_id,
> i.trans_id
> from deleted d, inserted i
> where d.user_init = i.user_init
> return
> go
> /* ***************************** */
> create trigger transaction_touch_instrg
> on transaction_touch
> for insert
> as
> declare @.num_rows int,
> @.count_num_rows int,
> @.errmsg varchar(255)
> select @.num_rows = @.@.rowcount
> if @.num_rows = 0
> return
> insert into als_run_touch
> (als_module_group_id, operation, entity_name,key1,key2,
> key3,key4,key5,key6,key7,key8,trans_id,sequence,to uch_key)
> select a.als_module_group_id,
> case when i.operation = 'INSERT' then 'I'
> when i.operation = 'UPDATE' then 'U'
> when i.operation = 'DELETE' then 'D'
> end,
> i.entity_name,
> i.key1,
> i.key2,
> i.key3,
> i.key4,
> i.key5,
> i.key6,
> i.key7,
> i.key8,
> i.trans_id,
> i.sequence,
> i.touch_key
> from als_module_entity a,
> inserted i
> where ( ( ((a.operation_type_mask & 1) = 1) and (i.operation =
> 'INSERT') ) OR
> ( ((a.operation_type_mask & 2) = 2) and (i.operation =
> 'UPDATE') ) OR
> ( ((a.operation_type_mask & 4) = 4) and (i.operation =
> 'DELETE') ) ) AND
> (a.entity_name = i.entity_name)
> return
> go
>
> The aud_icts_user table does not have triggers. I hope this help
>
> -- Peter Lo
>
> "Shelby Goerlitz [MSFT]" <shelbyg@.nospam.microsoft.com> wrote in message
> news:uaP2%235whFHA.2180@.TK2MSFTNGP15.phx.gbl...
> Java
> an
> rows
> were
> driver
>
|||Peter,
I used the following SQL to create some DB tables and triggers for my
testing and determined that the behavior you are seeing is by design.
The MS SQL Server driver for JDBC does not have the means to return the
update count for the statement executed by the application when that
statement causes other SQL DML statements to be executed via a trigger.
create table trig1(col1 int, col2 char(5))
create table trig2(col1 int, col2 char(5))
create table trig3(col1 int, col2 char(5))
create trigger inserttrig1
on trig1
for insert
as
if update(col1)
begin
insert into trig2 values(1,'row')
end
create trigger inserttrig2
on trig2
for insert
as
if update(col1)
begin
update trig3 set col1=1 where col2='none'
end
The inserttrig2 trigger will never affect any rows as there are no rows
in the trig3 table. This is intentional. I used a simple JDBC app to
insert a row into the trig1 table so I could see what kind of update
count was returned. With the MS SQL Server driver for JDBC, an update
count of 0 was returned as I expected. This is the update count for
the execution of the inserttrig2 trigger. Due to the way SQL Server
executes triggers and the resulting TDS packet sent to the driver upon
completion, the update count returned corresponds to the most nested
SQL statement that was executed in a trigger.
For example, if my application execute an insert statement that results
in trigger1 performing and insert which results in trigger2 performing
and update, then the results returned to the application are in the
order trigger2 update count, trigger1 update count, application
statement update count.
I ran a second test using the 3.5 DataDirect SQL Server driver for JDBC
and saw an update count of 1 returned which corresponded to the update
count for the initial insert. This is the correct behavior as the
DataDirect driver has the connection option alwaysReportTriggerResults
which defaults to false. As a result, the driver parses the results
and discards update counts for trigger that are returned by the server.
This results in the driver returning the update count for the
statement executed by the app.
When I set this option to true, then an update count of zero is
returned thereby behaving the same as the MS driver as expected.
If you wish to take advantage of this functionality, then I suggest
downloading the DataDirect driver and taking it for a spin. You can
download from here:
http://www.datadirect.com/download/index.ssp
-Brian
Brian Derwart
DataDirect Technologies SupportLink

ExecuteSQL Fails from Variable

I am executing the following statement to setup a database:

IF EXISTS (SELECT name FROM master.dbo.sysdatabases WHERE name = N'WTemplate')

BEGIN

ALTER DATABASE [WTemplate] SET SINGLE_USER WITH ROLLBACK IMMEDIATE

DROP DATABASE [WTemplate]

END

GO

CREATE DATABASE WTemplate ON PRIMARY

( NAME = N'WTemplate', FILENAME = N'D:\MSSQL\MSSQL.1\MSSQL\DATA\WTemplate.mdf' , SIZE = 2048KB , FILEGROWTH = 1024KB )

LOG ON

( NAME = N'WTemplate_log', FILENAME = N'D:\MSSQL\MSSQL.1\MSSQL\DATA\WTemplate_log.ldf' , SIZE = 1024KB , FILEGROWTH = 10%)

GO

EXEC dbo.sp_dbcmptlevel @.dbname=N'WTemplate', @.new_cmptlevel=90

GO

EXEC WTemplate.[dbo].[sp_fulltext_database] @.action = 'disable'

GO

ALTER DATABASE WTemplate SET ANSI_NULL_DEFAULT OFF

GO

ALTER DATABASE WTemplate SET ANSI_NULLS OFF

GO

ALTER DATABASE WTemplate SET ANSI_PADDING OFF

GO

ALTER DATABASE WTemplate SET ANSI_WARNINGS OFF

GO

ALTER DATABASE WTemplate SET ARITHABORT OFF

GO

ALTER DATABASE WTemplate SET AUTO_CLOSE OFF

GO

ALTER DATABASE WTemplate SET AUTO_CREATE_STATISTICS ON

GO

ALTER DATABASE WTemplate SET AUTO_SHRINK OFF

GO

ALTER DATABASE WTemplate SET AUTO_UPDATE_STATISTICS ON

GO

ALTER DATABASE WTemplate SET CURSOR_CLOSE_ON_COMMIT OFF

GO

ALTER DATABASE WTemplate SET CURSOR_DEFAULT GLOBAL

GO

ALTER DATABASE WTemplate SET CONCAT_NULL_YIELDS_NULL OFF

GO

ALTER DATABASE WTemplate SET NUMERIC_ROUNDABORT OFF

GO

ALTER DATABASE WTemplate SET QUOTED_IDENTIFIER OFF

GO

ALTER DATABASE WTemplate SET RECURSIVE_TRIGGERS OFF

GO

ALTER DATABASE WTemplate SET RECOVERY FULL

GO

ALTER DATABASE WTemplate SET MULTI_USER

GO

ALTER DATABASE WTemplate SET PAGE_VERIFY CHECKSUM

GO

If this is formed inside a script task, assigned to a variable and then executed from the variable it fails. If I past it into the Execute SQL Task as a string it succeeds. Any ideas on where the difference may be? I have set a breakpoint and verified that the variable is being filled in correctly.

I get this error:

SSIS package "BuildTemplates.dtsx" starting.

Error: 0x0 at Create Database: Incorrect syntax near the keyword 'CREATE'.

Error: 0x0 at Create Database: Incorrect syntax near 'GO'.

Error: 0x0 at Create Database: Incorrect syntax near 'GO'.

Error: 0x0 at Create Database: Incorrect syntax near 'GO'.

Error: 0x0 at Create Database: Incorrect syntax near 'GO'.

Error: 0x0 at Create Database: Incorrect syntax near 'GO'.

Error: 0x0 at Create Database: Incorrect syntax near 'GO'.

Error: 0x0 at Create Database: Incorrect syntax near 'GO'.

Error: 0x0 at Create Database: Incorrect syntax near 'GO'.

Error: 0x0 at Create Database: Incorrect syntax near 'GO'.

Error: 0x0 at Create Database: Incorrect syntax near 'GO'.

Error: 0x0 at Create Database: Incorrect syntax near 'GO'.

Error: 0x0 at Create Database: Incorrect syntax near 'GO'.

Error: 0x0 at Create Database: Incorrect syntax near 'GO'.

Error: 0x0 at Create Database: Incorrect syntax near 'GO'.

Error: 0x0 at Create Database: Incorrect syntax near 'GO'.

Error: 0x0 at Create Database: Incorrect syntax near 'GO'.

Error: 0x0 at Create Database: Incorrect syntax near 'GO'.

Error: 0x0 at Create Database: Incorrect syntax near 'GO'.

Error: 0x0 at Create Database: Incorrect syntax near 'GO'.

Error: 0x0 at Create Database: Incorrect syntax near 'GO'.

Error: 0xC002F210 at Create Database, Execute SQL Task: Executing the query "IF EXISTS (SELECT name FROM master.dbo.sysdatabases WHERE name = N'WTemplate')

BEGIN

ALTER DATABASE [WTemplate] SET SINGLE_USER WITH ROLLBACK IMMEDIATE

DROP DATABASE [WTemplate]

END

GO

CREATE DATABASE WTemplate ON PRIMARY

( NAME = N'WTemplate', FILENAME = N'D:\MSSQL\MSSQL.1\MSSQL\DATA\WTemplate.mdf' , SIZE = 2048KB , FILEGROWTH = 1024KB )

LOG ON

( NAME = N'WTemplate_log', FILENAME = N'D:\MSSQL\MSSQL.1\MSSQL\DATA\WTemplate_log.ldf' , SIZE = 1024KB , FILEGROWTH = 10%)

GO

EXEC dbo.sp_dbcmptlevel @.dbname=N'WTemplate', @.new_cmptlevel=90

GO

EXEC WTemplate.[dbo].[sp_fulltext_database] @.action = 'disable'

GO

ALTER DATABASE WTemplate SET ANSI_NULL_DEFAULT OFF

GO

ALTER DATABASE WTemplate SET ANSI_NULLS OFF

GO

ALTER DATABASE WTemplate SET ANSI_PADDING OFF

GO

ALTER DATABASE WTemplate SET ANSI_WARNINGS OFF

GO

ALTER DATABASE WTemplate SET ARITHABORT OFF

GO

ALTER DATABASE WTemplate SET AUTO_CLOSE OFF

GO

ALTER DATABASE WTemplate SET AUTO_CREATE_STATISTICS ON

GO

ALTER DATABASE WTemplate SET AUTO_SHRINK OFF

GO

ALTER DATABASE WTemplate SET AUTO_UPDATE_STATISTICS ON

GO

ALTER DATABASE WTemplate SET CURSOR_CLOSE_ON_COMMIT OFF

GO

ALTER DATABASE WTemplate SET CURSOR_DEFAULT GLOBAL

GO

ALTER DATABASE WTemplate SET CONCAT_NULL_YIELDS_NULL OFF

GO

ALTER DATABASE WTemplate SET NUMERIC_ROUNDABORT OFF

GO

ALTER DATABASE WTemplate SET QUOTED_IDENTIFIER OFF

GO

ALTER DATABASE WTemplate SET RECURSIVE_TRIGGERS OFF

GO

ALTER DATABASE WTemplate SET RECOVERY FULL

GO

ALTER DATABASE WTemplate SET MULTI_USER

GO

ALTER DATABASE WTemplate SET PAGE_VERIFY CHECKSUM

GO

" failed with the following error: "Incorrect syntax near 'GO'.". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.

I suspect what is going on is that the \ in the paths need to be doubled. I did that and the problem appeared to go away.

Thanks,

ExecuteScalarProblem

 In my application Im inserting data into the database and returning the ID of the new record, to do this I have the following stored procedure: 
 
ALTER PROCEDURE Turbo_InsertAppChange(@.app_namevarchar(50),@.app_developerchar(3),@.app_rq_numchar(10),@.app_completition_datedatetime, @.app_descriptionvarchar(1500))AS SET NOCOUNT ON INSERT INTO Turbo_Change_Log(app_name,app_developer,app_rq_num,app_completition_date,app_description,date_entered)SELECT @.app_name, @.app_developer, @.app_rq_num,CONVERT(DATETIME,@.app_completition_date), @.app_description,GETDATE()SELECT SCOPE_IDENTITY()
Where I use this procedure I have this code:

 
Protected Sub EnterAppInfo()'##INSERT APP INFO## sSQL ="Turbo_InsertAppChange" Command =New SqlCommand(sSQL, Connection) Command.CommandType = CommandType.StoredProcedure Command.Parameters.Add("@.app_name", SqlDbType.VarChar).Value = application_name.Text.ToString Command.Parameters.Add("@.app_developer", SqlDbType.Char).Value = developer_list.SelectedValue.ToString Command.Parameters.Add("@.app_rq_num", SqlDbType.VarChar).Value = rq_num.Text.ToString Command.Parameters.Add("@.app_completition_date", SqlDbType.DateTime).Value =CType(Api_calendar1.DDate,Date) Command.Parameters.Add("@.app_description", SqlDbType.VarChar).Value = proj_desc.Text.ToStringTry Connection.Open()Dim NewIdAs Integer =CType(Command.ExecuteScalar(),Integer)
...

But I'm getting theObject reference not set to an instance of an object error at theDim NewId As Integer = CType(Command.ExecuteScalar(),Integer) line. When I run this procedure alone in QueryAnalyzer it returns the ID like its supposed to, but when I run it in my application I get the above error. What am I doing wrong here?

ExecuteScalar return null reference if the result set is empty.

So you convert a null object to integer which cause the error:

CType(Command.ExecuteScalar(),Integer)

You can catch the exeption and return 0(means null).

ExecuteScalar() Returns -1

The following query returns 0 when executing in Query Analyzer:
SELECT isnull(Count(*),0) as total FROM SplitDetail WHERE SiteCode = 14 AND ProjectID = 4367
Yet ExecuteScalar() in vb.net return a -1.

Any ideas on what I might be doing wrong... ?Discovered my error...

The ExecuteScalar method deep in the plumbing of my DAL was actually calling an ExecuteNonQuery() function...

ExecuteScalar returns null

I am using the following C# code and T-SQL to get result object from a
SQL Server database. When my application runs, the ExecuteScalar
returns "10/24/2006 2:00:00 PM" if inserting a duplicated record. It
returns null for all other conditions. Does anyone know why? Does
anyone know how to get the output value? Thanks.

-- C# --
aryParams = {'10/24/2006 2pm', '10/26/2006 3pm', 2821077, null};
object oRtnObject = null;
StoredProcCommandWrapper =
myDb.GetStoredProcCommandWrapper(strStoredProcName ,aryParams);
oRtnObject = myDb.ExecuteScalar(StoredProcCommandWrapper);

-- T-SQL --
ALTER PROCEDURE [dbo].[procmyCalendarInsert]
@.pBegin datetime,
@.pEnd datetime,
@.pUserId int,
@.pOutput varchar(200) output
AS
BEGIN
SET NOCOUNT ON;

select * from myCalendar
where beginTime >= @.pBegin and endTime <= @.pEnd and userId = @.pUserId

if @.@.rowcount <0
begin
print 'Path 1'
set @.pOutput = 'Duplicated reservation'
select @.pOutput as 'Result'
return -1
end
else
begin
print 'Path 2'
-- check if upperlimit (2) is reached
select rtrim(cast(beginTime as varchar(30))) + ', ' +
rtrim(cast(endTime as varchar(30)))
,count(rtrim(cast(beginTime as varchar(30))) + ', ' +
rtrim(cast(endTime as varchar(30))))
from myCalendar
group by rtrim(cast(beginTime as varchar(30))) + ', ' +
rtrim(cast(endTime as varchar(30)))
having count(rtrim(cast(beginTime as varchar(30))) + ', ' +
rtrim(cast(endTime as varchar(30)))) =2
and (rtrim(cast(beginTime as varchar(30))) + ', ' +
rtrim(cast(endTime as varchar(30))) =
rtrim(cast(@.pBegin as varchar(20)))+ ', ' + rtrim(cast(@.pEnd as
varchar(20))))

-- If the @.@.rowcount is not equal to 0 then
-- at the time between @.pBegin and @.pEnd the maximum count of 2 is
reached

if @.@.rowcount <0
begin
print 'Path 3'
set @.pOutput = '2 reservations are already taken for the hours'
select @.pOutput as 'Result'
return -1
end
else
begin
print 'Path 4'
--safe to insert
insert dbo.myCalendar(beginTime, endTime,userId)
values (@.pBegin, @.pEnd, @.pUserId)
if @.@.error = 0
begin
print 'Path 4:1 @.@.error=' + cast(@.@.error as varchar(1))
print 'Path 4:1 @.@.rowcount=' + cast(@.@.rowcount as varchar(1))
set @.pOutput = 'Reservation succeeded'
select @.pOutput as 'Result'
return 0
end
else
begin
print 'Path 4:2 @.@.rowcount=' + cast(@.@.rowcount as varchar(1))
set @.pOutput = 'Failed to make reservation'
select @.pOutput as 'Result'
return -1
end
end
end
ENDjs wrote:

Quote:

Originally Posted by

I am using the following C# code


There was no way for you to know it (except maybe by browsing through some
of the previous questions in this newsgroup before posting yours - always a
recommended practice) , but this is a classic ADO newsgroup. ADO.Net bears
very little resemblance to classic ADO so, while you may be lucky enough to
find a dotnet-knowledgeable person here who can answer your question, you
can eliminate the luck factor by posting your question to a group where
those dotnet-knowledgeable people hang out. I suggest
microsoft.public.dotnet.framework.adonet.

But read on:

Quote:

Originally Posted by

and T-SQL to get result object from a
SQL Server database. When my application runs, the ExecuteScalar
returns "10/24/2006 2:00:00 PM" if inserting a duplicated record. It
returns null for all other conditions. Does anyone know why? Does
anyone know how to get the output value? Thanks.
>
-- C# --
aryParams = {'10/24/2006 2pm', '10/26/2006 3pm', 2821077, null};
object oRtnObject = null;
StoredProcCommandWrapper =
myDb.GetStoredProcCommandWrapper(strStoredProcName ,aryParams);
oRtnObject = myDb.ExecuteScalar(StoredProcCommandWrapper);
>
-- T-SQL --
ALTER PROCEDURE [dbo].[procmyCalendarInsert]
@.pBegin datetime,
@.pEnd datetime,
@.pUserId int,
@.pOutput varchar(200) output
AS
BEGIN
SET NOCOUNT ON;
>
select * from myCalendar
where beginTime >= @.pBegin and endTime <= @.pEnd and userId = @.pUserId
>
if @.@.rowcount <0


This is extremely misguided. Not only is it grossly inefficient, retrieving
all the records that meet the requirements, it is also preventing you from
retrieving your output value. SQL Server does not send RETURN and OUTPUT
parameter values to the client until all resultsets are sent. The above
select statement is creating a resultset that wwill be sent to the client.

If you want to verify if records exist, use IF EXISTS, as in

IF EXISTS (select * from myCalendar
where beginTime >= @.pBegin and endTime <= @.pEnd and userId = @.pUserId)

This is more efficient because it does not retrieve a resultset, it only
verifies that the records meeting therequirements exist. If you really want
a count of the records that meet the requirements (which does not seem to be
te case here) you should use:

declare @.cnt int
Set @.cnt= (select count(*) from myCalendar
where beginTime >= @.pBegin and endTime <= @.pEnd and userId = @.pUserId)

Because the result is assigned to a variable, no resultset is created that
needs to be sent to the client.

Quote:

Originally Posted by

begin
print 'Path 1'
set @.pOutput = 'Duplicated reservation'
select @.pOutput as 'Result'
return -1
end
else
begin
print 'Path 2'
-- check if upperlimit (2) is reached
select rtrim(cast(beginTime as varchar(30))) + ', ' +
rtrim(cast(endTime as varchar(30)))
,count(rtrim(cast(beginTime as varchar(30))) + ', ' +
rtrim(cast(endTime as varchar(30))))
from myCalendar
group by rtrim(cast(beginTime as varchar(30))) + ', ' +
rtrim(cast(endTime as varchar(30)))
having count(rtrim(cast(beginTime as varchar(30))) + ', ' +
rtrim(cast(endTime as varchar(30)))) =2
and (rtrim(cast(beginTime as varchar(30))) + ', ' +
rtrim(cast(endTime as varchar(30))) =
rtrim(cast(@.pBegin as varchar(20)))+ ', ' + rtrim(cast(@.pEnd as
varchar(20))))


I'm not sure what the point of the above concatenation is: are you trying to
present a datetime in a particular format? If so, are you aware that

Quote:

Originally Posted by

>
-- If the @.@.rowcount is not equal to 0 then
-- at the time between @.pBegin and @.pEnd the maximum count of 2 is
reached


You do realize that because of the intervening statements, the @.@.rowcount
function returns a different value than was returned the first time you used
it ... ? @.@.error and @.@.rowcount are only useful if used immediately after
the statement you wish to test. New statements cause these functions to
return new values.

Anyways, you already determined above that the records exist. Why bother
checking again?

Quote:

Originally Posted by

>
if @.@.rowcount <0


Bob Barrows

--
Microsoft MVP - ASP/ASP.NET
Please reply to the newsgroup. This email account is my spam trap so I
don't check it very often. If you must reply off-line, then remove the
"NO SPAM"

Monday, March 19, 2012

ExecuteNonQuery in SQL 2005

I have an ASP.Net page that runs the following command which is giving me
the following SQL error:
The statement has been terminated.
Subquery returned more than 1 value. This is not permitted when the subquery
follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
The code in the page is as follows:
strSQL = "EXEC fd_insFileTaskDefaultsNew " & lngNextFile & ", " &
Request.Form("cboFileTypeID") & ", 0"
cmd = New OleDbCommand(strSQL, conFileData)
lngRows = cmd.ExecuteNonQuery()
It is failing on the last statement and I don't know why. Also, below is
the stored proc code. Can anyone help? Thanks
David
CREATE PROCEDURE dbo.fd_insFileTaskDefaultsNew
(
@.FileNumber int,
@.FileTypeID int,
@.Rows int output
)
AS
/* SET NOCOUNT ON */
INSERT INTO FileTasks
(FileNumber, TaskTitle, TaskDate, PrimaryID, NotifyDate, TaskNotes,
AssignedID)
SELECT @.FileNumber, TaskTitle,
DATEADD(day, TaskDaysOut, GETDATE()), PrimaryID,
CONVERT(char(10), GETDATE(), 101), TaskNotes, AssignedID
FROM FileTaskDefaults
WHERE FileTypeID = @.FileTypeID
RETURN @.RowsTry executing the stored procedure directly from query analyzer and see if
you get the same error?
"David" <dlchase@.lifetimeinc.com> wrote in message
news:uQdZVqTbGHA.1204@.TK2MSFTNGP04.phx.gbl...
> I have an ASP.Net page that runs the following command which is giving me
> the following SQL error:
> The statement has been terminated.
> Subquery returned more than 1 value. This is not permitted when the
subquery
> follows =, !=, <, <= , >, >= or when the subquery is used as an
expression.
> The code in the page is as follows:
> strSQL = "EXEC fd_insFileTaskDefaultsNew " & lngNextFile & ", " &
> Request.Form("cboFileTypeID") & ", 0"
> cmd = New OleDbCommand(strSQL, conFileData)
> lngRows = cmd.ExecuteNonQuery()
> It is failing on the last statement and I don't know why. Also, below is
> the stored proc code. Can anyone help? Thanks
> David
>
> CREATE PROCEDURE dbo.fd_insFileTaskDefaultsNew
> (
> @.FileNumber int,
> @.FileTypeID int,
> @.Rows int output
> )
> AS
> /* SET NOCOUNT ON */
> INSERT INTO FileTasks
> (FileNumber, TaskTitle, TaskDate, PrimaryID, NotifyDate, TaskNotes,
> AssignedID)
> SELECT @.FileNumber, TaskTitle,
> DATEADD(day, TaskDaysOut, GETDATE()), PrimaryID,
> CONVERT(char(10), GETDATE(), 101), TaskNotes, AssignedID
> FROM FileTaskDefaults
> WHERE FileTypeID = @.FileTypeID
> RETURN @.Rows
>|||Yes, same error.
David
"Jim Underwood" <james.underwoodATfallonclinic.com> wrote in message
news:uqtyUzTbGHA.3992@.TK2MSFTNGP05.phx.gbl...
> Try executing the stored procedure directly from query analyzer and see if
> you get the same error?
> "David" <dlchase@.lifetimeinc.com> wrote in message
> news:uQdZVqTbGHA.1204@.TK2MSFTNGP04.phx.gbl...
> subquery
> expression.
>|||Is FileTaskDefaults a view?
Are there any triggers on FileTasks?
David
"David" <dlchase@.lifetimeinc.com> wrote in message
news:ugsFP3TbGHA.504@.TK2MSFTNGP03.phx.gbl...
> Yes, same error.
> David
> "Jim Underwood" <james.underwoodATfallonclinic.com> wrote in message
> news:uqtyUzTbGHA.3992@.TK2MSFTNGP05.phx.gbl...
>|||It doesn't look to me that your output parameter is ever assigned to
any value. Don't you need something like this
SELECT @.FileNumber, TaskTitle,
DATEADD(day, TaskDaysOut, GETDATE()), PrimaryID,
CONVERT(char(10), GETDATE(), 101), TaskNotes, AssignedID
FROM FileTaskDefaults
WHERE FileTypeID = @.FileTypeID
-- assign row count to @.Rows
SELECT @.Rows = @.@.Rowcount|||> RETURN @.Rows
Where does this value get populated? Do you want to use a RETURN, OUTPUT,
or both? I suggest sticking to output parameters for this kind of data, and
not using RETURN. RETURN is meant to return a status code (e.g.
success/failure), not data. This is one of the reasons they're limited to
INTeger datatypes.
A|||That was it! I removed the trigger and it worked. Thank you.
David
"David Browne" <davidbaxterbrowne no potted meat@.hotmail.com> wrote in
message news:%23%236acDUbGHA.4912@.TK2MSFTNGP05.phx.gbl...
> Is FileTaskDefaults a view?
> Are there any triggers on FileTasks?
> David
> "David" <dlchase@.lifetimeinc.com> wrote in message
> news:ugsFP3TbGHA.504@.TK2MSFTNGP03.phx.gbl...
>|||> That was it! I removed the trigger and it worked. Thank you.
I don't see how that is possible, unless either
(a) you didn't post all of the stored procedure code in your original post,
or
(b) you eliminated the error, but you aren't actually verifying that the
stored procedure is correctly returning the rowcount.
Anyway, it sounds like your trigger was written expecting only single-row
row modifications. You should re-visit that logic instead of just throwing
the trigger away, especially if the trigger is not yours and you are not
sure what it was doing.|||David (dlchase@.lifetimeinc.com) writes:
> That was it! I removed the trigger and it worked. Thank you.
And the trigger did not serve any purpose? Yeah, maybe it was just an
old relic, but I get nervous when I hear things like this. Just because
you did not get any error message, does not mean that it worked. If you
removed a trigger that performed some important task to maintain database
integrity, I would not call that working...
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|||hopefully the OP removed to trigger temporarily just to confirm that was the
issue and is rewriting the trigger to correct the subquery.
"Erland Sommarskog" <esquel@.sommarskog.se> wrote in message
news:Xns97B6D62F991A4Yazorman@.127.0.0.1...
> David (dlchase@.lifetimeinc.com) writes:
> And the trigger did not serve any purpose? Yeah, maybe it was just an
> old relic, but I get nervous when I hear things like this. Just because
> you did not get any error message, does not mean that it worked. If you
> removed a trigger that performed some important task to maintain database
> integrity, I would not call that working...
> --
> 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

ExecuteNonQuery error

When I try to insert a record with the ExecuteNonQuery command, I get the following error information. Any clues why? Thanks.

SSqlException was unhandled by user code
...
Message="Incorrect syntax near [output of one of my field names]."
...
[Item detail:] In order to evaluate an indexed property, the property must be qualified and the arguments must be explicitly supplied by the user.

My code:

Private objCmdAs SqlCommand
Private strConnAsNew SqlConnection(ConfigurationManager.AppSettings("conn"))
...
objCmd =New SqlCommand("INSERT INTO tblUsers (UserID,FName,LName,PrimLang1,Ctry,Phone)" & _
"VALUES('" & strUser &"','" & strFName.Text &"','" & strLName.Text &"', '" & strLang.Text &"', '" & strCtry.Text &"', '" & strPhone.Text &"'" _
, strConn)
strConn.Open()
objCmd.ExecuteNonQuery()

hi muybn,

there's not closing bracket for values() i mean

objCmd =New SqlCommand("INSERT INTO tblUsers (UserID,FName,LName,PrimLang1,Ctry,Phone)" & _
"VALUES('" & strUser &"','" & strFName.Text &"','" & strLName.Text &"', '" & strLang.Text &"', '" & strCtry.Text &"', '" & strPhone.Text &"')" _ 'can u see please i added a bracket )
, strConn)

regards,

satish.

|||Don't concatenate UI-supplied data to SQL statements that will be executed. This is an insecure practice as it opens up your server to SQL injection attacks. Use parameters instead.|||

Thanks, but doesn't the closing parenthesis bracket go after the reference to the connection string, in this case on the last line, strConn)?

|||

Thanks, TMorton. Is this merely a security precaution or would it cause the error I'm experiencing?

I plan to incorporate parameters into my project before I take it live. Can you point me to a definitive tutorial source for forming parameters, or better yet, mock up some of the variables that I've supplied above into parameters? To be honest, I've looked at quite a few sites and they've all confused me with how to define the parameters after the SQL statement, where you set the parameters equal to the variables.

|||

What Terri is recommending is

1) considered a best practice
2) offers protection from sql injection
3) avoids issues with getting your quotes correct when concatenating the sql. (have you considered what happens if a lastname is "O'Rourke")

Dim objCmdAs SqlCommandDim strConnAs New SqlConnection(ConfigurationManager.AppSettings("conn"))'... objCmd.Parameters.Add(New SqlParameter("@.p1", strUser)) objCmd.Parameters.Add(New SqlParameter("@.p2", strFName.Text)) objCmd.Parameters.Add(New SqlParameter("@.p3", strLName.Text)) objCmd.Parameters.Add(New SqlParameter("@.p4", strLang.Text)) objCmd.Parameters.Add(New SqlParameter("@.p5", strCtry.Text)) objCmd.Parameters.Add(New SqlParameter("@.p6", strPhone.Text)) objCmd =New SqlCommand("INSERT INTO tblUsers (UserID,FName,LName,PrimLang1,Ctry,Phone)" & _" VALUES(@.p1,@.p2,@.p3,@.p4,@.p5,@.p6)", strConn) strConn.Open() objCmd.ExecuteNonQuery()
|||

still good option is write stored procedures wherever necessary, they are better in performance as they are precompiled. rest what mike has given as example is good one.

and for earlier post values clause has its own brackets so you need to close where i mentioned earlier.

thanks,

satish

|||Thanks, now I see. Hopefully it will work now.|||

satish_nagdev:

still good option is write stored procedures wherever necessary, they are better in performance as they are precompiled.

Performance differences between dynamic sql and stored procs is one of those things that is widely disputed. Personally i'm quite fond of dynamic sql but will still use a sproc if i see a benefit. But, rather than just debate the issue, let's test it. Here I offer the results of a very simple performance test.

IterationDynSqlSproc10.0003820.00023520.0001760.00017430.0001490.00016440.0001390.00015150.0001650.00016860.0001420.00015970.0001410.00015080.0001610.00016790.0001430.000159100.0001410.000150

Since the execution plan for dynamic sql is also cached (as is the execution plan for a sproc), the dynamic sql actually turns out to be quite performant.
Note that on iteration 1, the dynamic sql suffered a little because i ran it first. If i had run the sproc first, the result would look more like this:

IterationDynSqlSproc10.0001850.00038320.0001430.00016030.0001400.00015340.0004810.00017250.0001580.00020460.0001380.00015370.0001390.00014880.0001510.00017290.0001440.000149100.0001400.000147

Both set of results were taken after running my test code a few times to try to be more consistent with how a system in motion might perform.

Of course test results mean nothing unless you know how the test was run. I ran the test on my development system where sql 2000 was also installed on the same box.

This is the test code. Please adapt it to your own real word test to see if dynamic sql can compete with your own sprocs.

The test sproc:

CREATE PROCEDURE GetUserActivity (@.userid integer)AS-- tblTransactionLog has 1 million+ rows of data-- the userid column is indexedSELECT *FROM tblTransactionLogWHERE userid = @.userId;GO

The page code:

Protected Sub Page_Load(ByVal senderAs Object,ByVal eAs System.EventArgs)Handles Me.LoadDim swAs StopwatchDim drAs SqlDataReaderDim connAs SqlConnectionDim cmdDynamicAs New SqlCommandDim cmdSprocAs New SqlCommandDim dynParamAs SqlParameterDim sprocParamAs SqlParameterDim tsDynamicAs TimeSpanDim tsSprocAs TimeSpan conn =New SqlConnection("Initial Catalog=webcommon;Integrated Security=True") dynParam =New SqlParameter("@.userid", SqlDbType.Int, 4) dynParam.Value = 4347 cmdDynamic.Parameters.Add(dynParam) sprocParam =New SqlParameter("@.userid", SqlDbType.Int, 4) sprocParam.Value = 4347 cmdSproc.Parameters.Add(sprocParam) conn.Open() Using conn'prepare for sproc cmdDynamic.CommandText ="GetUserActivity" cmdDynamic.CommandType = CommandType.StoredProcedure cmdDynamic.Connection = conn'prepare for dynsql cmdSproc.CommandText ="select * from tblTransactionLog where userid = @.userid;" cmdSproc.CommandType = CommandType.Text cmdSproc.Connection = conn Response.Write("<table border=""1""><tr><th>Iteration</th><th>DynSql</th><th>Sproc</th></tr>")For indexAs Integer = 1To 10'going first incurs a small performance penalty on the very first iteration sw = Stopwatch.StartNew dr = cmdSproc.ExecuteReader() tsSproc = sw.Elapsed dr.Close() sw = Stopwatch.StartNew dr = cmdDynamic.ExecuteReader() tsDynamic = sw.Elapsed dr.Close() Response.Write(String.Format("<tr><td>{0}</td><td>{1}</td><td>{2}</td></tr>", index, tsDynamic.TotalSeconds.ToString("n6"), tsSproc.TotalSeconds.ToString("n6")))Next Response.Write("</table>")End UsingEnd Sub
|||

satish_nagdev:

still good option is write stored procedures wherever necessary, they are better in performance as they are precompiled.

This is misguided advice. There are good reasons to use stored procedures, but performance is not one of them. There are places where *not* using stored procedures is a better option. This topic (stored procedures vs. inline SQL) is the subject of a lot of heated, well-reasoned discussion in the blogosphere.

|||How awesome that you would take the time to detail all this for me! Thanks. I will test it out soon. Right now, I have to go one step at a time understanding the underlying principles and solving some other errors that are showing up.|||Mike, I'm getting this error while trying to use your suggestion on parameters: "Object reference not set to an instance of an object." This comes with each line that begins with "objCmd.Parameters." These are merely strings, as far as I can see, so I don't know why it would be asking for object instances.|||

my bad. when adapting your code i got it out of sequence...you need to create the command object before you add the parameters.

Dim objCmdAs SqlCommandDim strConnAs New SqlConnection(ConfigurationManager.AppSettings("conn")) objCmd =New SqlCommand("INSERT INTO tblUsers (UserID,FName,LName,PrimLang1,Ctry,Phone)" & _" VALUES(@.p1,@.p2,@.p3,@.p4,@.p5,@.p6)", strConn) objCmd.Parameters.Add(New SqlParameter("@.p1", strUser)) objCmd.Parameters.Add(New SqlParameter("@.p2", strFName.Text)) objCmd.Parameters.Add(New SqlParameter("@.p3", strLName.Text)) objCmd.Parameters.Add(New SqlParameter("@.p4", strLang.Text)) objCmd.Parameters.Add(New SqlParameter("@.p5", strCtry.Text)) objCmd.Parameters.Add(New SqlParameter("@.p6", strPhone.Text)) strConn.Open() objCmd.ExecuteNonQuery()
|||

Terri, Mike,

i wont argue on that. I agree with you guys upto a limit, but mike in my last project there were heaps of inline queries we found while re-writing the application, so using procedures added positively to scalability. so depends on from situation to situation.

mike you've done testing thats good, if you get time could you do it for simultaneous instances say 10 at a go?

thanks,

satish.

|||

Inline queries should by managed in a DAL Component. My DAL is a seperate project which keeps things nice and tidy.
I actually have very few hand typed dynamic sql statements. My dynamic sql is about 99% generated on the fly.

Anyways, I put my test page through an ACT test script and here are the results. I used only 8 simultaneous connections to avoid a resultset with http errors .

Test 1 - sproc performance:

commented out the dynamic reader code inside the loop
test duration: 1 minute
Avg Requests per second: 587
Total requests completed: 35,232

Test 2 - dynamic sql performance:

commented out the sproc reader code inside the loop
test duration: 1 minute
Avg Requests per second: 601
Total requests completed: 36,082

My test setup is a little flawed since my test script was running on the same system that was under test. But, since we're just doing a head to head comparison and since both tests were subject to the same testing flaw, i'd have to conclude that dynamic sql (in this specific test case) outperformed a stored proc.

Execute() in class Microsoft.SqlServer.Dts.RunTime.Package has memory leak

The Execute method in Microsoft.SqlServer.Dts.RunTime.Package class has memory leak after each invokation. This following code demonstrates it.

Output from the program:

Allocated memory after 1 iteration(s) = 476316
Allocated memory after 2 iteration(s) = 546448
Allocated memory after 3 iteration(s) = 555008
Allocated memory after 4 iteration(s) = 563632
Allocated memory after 5 iteration(s) = 572232
Allocated memory after 6 iteration(s) = 580856
Allocated memory after 7 iteration(s) = 589480
Allocated memory after 8 iteration(s) = 598240
Allocated memory after 9 iteration(s) = 606816
Allocated memory after 10 iteration(s) = 615424
Allocated memory after 11 iteration(s) = 624000
Allocated memory after 12 iteration(s) = 632576
Allocated memory after 13 iteration(s) = 641152
Allocated memory after 14 iteration(s) = 649728
Allocated memory after 15 iteration(s) = 658352
Allocated memory after 16 iteration(s) = 666948
Allocated memory after 17 iteration(s) = 675760
Allocated memory after 18 iteration(s) = 684380
Allocated memory after 19 iteration(s) = 693008
Allocated memory after 20 iteration(s) = 701532

//--

// The Execute method in Microsoft.SqlServer.Dts.RunTime.Package has memory

// leak. This program demonstrates it. The package invoked by this program has

// only a single 'Script Task' that does nothing.

//

// To compile, add referece to Microsoft.SQLServer.ManagedDTS.dll.

//

// csc /r:"C:\Program Files\Microsoft SQL Server\90\SDK\Assemblies\Microsoft.SQLServer.ManagedDTS.dll" ExecPackage.cs

//

//--

using System;

using System.Diagnostics;

using Microsoft.SqlServer.Dts.Runtime;

namespace Misc

{

/// <summary>

/// Programmatically executes SSIS package, then displays memeory usage

/// after each execution. The memeory usage goes up after each

/// Package.Execute() call, which indicates memory leak!

/// </summary>

static class ExecPackage

{

static void DisplayUsage()

{

Console.WriteLine(@."Usage: ExecPackage <pkgName>");

Console.WriteLine(@." Package <pkgName> resides in Package Store on localhost under \File System\");

}

static void Main(string[] args)

{

// Parse command line arguments.

if (args.Length != 1)

{

DisplayUsage();

return;

}

string pkgName = @."\File System\" + args[0];

// Programmatically execute the package several times.

Application app = new Application();

for (int i = 1; i <= 20; i++)

{

Package pkg = app.LoadFromDtsServer(pkgName, "localhost", null);

pkg.Execute(); // comment out this line, then allocated memory does not increase

// Process.Start("dtexec.exe", "/dts \"" + pkgName + "\"");

pkg.Dispose();

pkg = null;

// Do garbage collection, then display memory usage

GC.Collect();

Console.WriteLine("Allocated memory after {0} iteration(s) = {1}",

i, GC.GetTotalMemory(true));

}

}

}

}

Thank you for the detailed posting and your time. I have gathered the information and we will investigate.

|||

Craig,

Are you able to confirm the issue? Is there a fix or workaround?

Thanks,

Bin

|||

Bin, yes we are able to reproduce the issue and we are reviewing it for inclusion into the next service pack. However at this time there is not real work around other than restarting the appliction that calls the package. Thank you again for your time and patience.

|||

Has there been any updates with this issue? I am currently dealing with the same problem.

Thanks,

Drew

|||

dferraro wrote:

Has there been any updates with this issue? I am currently dealing with the same problem.

Thanks,

Drew

the next service pack would be sp2, which has not yet been released.|||Thanks, but... is this really such a low priority it doesn't justify a hotfix? I'd say not being able to execut SSIS packages programmatically without having to write hacked code would be up on the top of their list... I know they had released a hotfix for the fuzzy lookup memory leak in the past... Is there anyone from MS who can confirm this is true?
Thanks again,
Drew|||Please advise...... we are looking to use this in a production environment, and I would like to know if/when this issue is fixed, so I can have better knowledge when deciding which options to pursue. How are other people dealing with this issue? Using dtexec? But what if you need to check return values, etc? Any other work-arounds besides building a composite app that runs the package and then dies off?

Thanks again,

Drew|||Looks like I'm having the same problem as well. I've got a .Net app that dynamically builds 120 tasks in a package and pulls in 3 million records running once an hour. I thought I had a memory leak with some other objects but it appears to happen whenever executing this package through the .Excecute() method in my app and still remains after destroying the object. Running this much data that often is going to be a real show stopper with a memory leak.|||The issue appears to be identified and we are working on the fix for a future Service pack.|||

Hello,

We have a production server which runs a nightly batch which is quite memory intensive. The batch contains a start package which is started by SQL Server Agent, and starts other packages using the "Execute Package Task".

The server crashes completely, without logging any error information at all, at random moments during the batch, usually with an interval of a few days. The vendor of the server is investigating the hardware configuration, but we weren't able to find a problem there as of yet.

Can the issue described in this topic have anything to do with the server crashes?

Kind regards, Jeroen