Showing posts with label command. Show all posts
Showing posts with label command. Show all posts

Thursday, March 29, 2012

executing SQL script from Command promt not working

Hello
I am trying to execute SQl script from command prom like this :

C:\Inetput\wwwroot> osql -U sa -P -i MyComics.sql

(uid=sa and pwd=)

and I got the result like this :

[Shared Memory]SQl Server deos not exist or access denied
[Shared Memory]Connection Open (Connect()).

I already check the SQL server , it's running.
what do I do now?

Thanks in advanceAre you certain that the user name and password is correct? Are you certain that this instance of SQL Server is the main instance and not a named instance?|||Hello

thank for the response.

from my understanding sa is the default user name of SQL Server 2000 and password is blank. I did not set any password for my SQL server.

I'm really new to SQL server, if you have any advice I'll appreciate.|||Try osql -E <other parameters, except user and password
-E uses a trusted connection. Unless you set an sa password while installing SQL Server, SQL Server is set to use Windows authentication. You need to specify Mixed Mode authentication. You can change to mixed mode security in Enterprise Manager. Right click database, select properties, set Authentication to SQL Server and Windows. Make sure you set a good sa password. DO NOT leave it as blank!

Executing SQL command when user is connecting

I would like to be able to limit users from connecting to the database using
other than the dedicated application. Of course it could be done using
application role, but the applicationd does not support this.
Therefore I have been writing some code to catch the bad guys, but how
should I trigger the code. Something like a trigger on sysprocesses would be
nice, but is not possible.
Any suggestions... ?
No...you'll need to create a job to check however often and execute
the code in the job.
-Sue
On Wed, 2 Jun 2004 22:20:23 +0200, "Ole Wissing"
<nospamtome@.mail.tele.dk> wrote:

>I would like to be able to limit users from connecting to the database using
>other than the dedicated application. Of course it could be done using
>application role, but the applicationd does not support this.
>Therefore I have been writing some code to catch the bad guys, but how
>should I trigger the code. Something like a trigger on sysprocesses would be
>nice, but is not possible.
>Any suggestions... ?
>
sql

Executing SQL command when user is connecting

I would like to be able to limit users from connecting to the database using
other than the dedicated application. Of course it could be done using
application role, but the applicationd does not support this.
Therefore I have been writing some code to catch the bad guys, but how
should I trigger the code. Something like a trigger on sysprocesses would be
nice, but is not possible.
Any suggestions... ?No...you'll need to create a job to check however often and execute
the code in the job.
-Sue
On Wed, 2 Jun 2004 22:20:23 +0200, "Ole Wissing"
<nospamtome@.mail.tele.dk> wrote:

>I would like to be able to limit users from connecting to the database usin
g
>other than the dedicated application. Of course it could be done using
>application role, but the applicationd does not support this.
>Therefore I have been writing some code to catch the bad guys, but how
>should I trigger the code. Something like a trigger on sysprocesses would b
e
>nice, but is not possible.
>Any suggestions... ?
>

Monday, March 26, 2012

Executing an update command after subscription

I need to execute an update stored procedure once the subscription report
has run.
The only way I can find to do this is to add an extra TSQL step into the SQL
Agent job through SQL Management Studio. But whenever the subscription is
modified via report manager, the newly added TSQL step is deleted.
Is there a way to get around this?
Cheers
GrantHello Grant,
My suggestion is create a new SQL Job and in this job, you could first
execute the job for the subscription and then you could add your extra
taskes. The schedule of this new job could be configured as you wish.
Once you create a subsciption in the report manager, the sql server agent
will create a job which have a GUID.
You could run the following TSQL statement to run the subscription job:
exec msdb..sp_start_job @.job_name='<GUID of the subscription job>'
Hope my suggestion will be helpful!
Sincerely,
Wei Lu
Microsoft Online Community Support
==================================================
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscriptions/managednewsgroups/default.aspx#notif
ications.
Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscriptions/support/default.aspx.
==================================================(This posting is provided "AS IS", with no warranties, and confers no
rights.)

Friday, March 23, 2012

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 File In Sql Query Analyzer

I Had A Text File In Which There Are Sqlstatements.i Want To Execute The Entire File In Query Analyzer.what Command I Must Use For That?

Quote:

Originally Posted by megastar5

I Had A Text File In Which There Are Sqlstatements.i Want To Execute The Entire File In Query Analyzer.what Command I Must Use For That?


Open the file in Query Analyzer, then hit F5.

Wednesday, March 21, 2012

Executing a command inside a read loop

How can I execute an SQL command inside a read loop? My code looks something
like this:
With cmd1.ExecuteReader
Do While .Read
cmd2.CommandText = "..."
Name = CStr(cmd2.ExecuteScalar)
Loop
.Close
End With
But it fails at the ExecuteScalar method, with an invalid operation
exception.ADO.NET 1 doesn't allow sending a query against a connection that you are cu
rrently using. Either
have a separate connection for cmd2, or cache the result from cmd1 immediate
and loop that cached
result.
Or, use ADO.NET 2.0, and read up on "MARS" (multiple active resultsets). You
need to set this
attribute in the connection string.
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
"Philip Sheard" <sheardp@.myisp.com> wrote in message news:Ois4sTHZGHA.3444@.TK2MSFTNGP05.phx
.gbl...
> How can I execute an SQL command inside a read loop? My code looks somethi
ng like this:
> With cmd1.ExecuteReader
> Do While .Read
> cmd2.CommandText = "..."
> Name = CStr(cmd2.ExecuteScalar)
> Loop
> .Close
> End With
> But it fails at the ExecuteScalar method, with an invalid operation except
ion.
>|||(I know this isn't the answer that you want to hear)
I would highly recommend looking into how your query is written. You
shouldn't have to loop through things like this. If you're trying to
append a column to the result set of a stored procedure, consider using
the INSERT EXEC syntax:
CREATE TABLE #ResultSet
(
:: <column-list>
)
INSERT #ResultSet
EXEC <procedure_name>
or, if the returned column-list is nondeterministic: SELECT a.*,
b.ColumnName FROM OPENQUERY('...', 'EXEC <procedure-name>') a,
<other_table> b
-Alan
Philip Sheard wrote:
> How can I execute an SQL command inside a read loop? My code looks somethi
ng
> like this:
> With cmd1.ExecuteReader
> Do While .Read
> cmd2.CommandText = "..."
> Name = CStr(cmd2.ExecuteScalar)
> Loop
> .Close
> End With
> But it fails at the ExecuteScalar method, with an invalid operation
> exception.|||Philip Sheard (sheardp@.myisp.com) writes:
> How can I execute an SQL command inside a read loop? My code looks
> something like this:
> With cmd1.ExecuteReader
> Do While .Read
> cmd2.CommandText = "..."
> Name = CStr(cmd2.ExecuteScalar)
> Loop
> .Close
> End With
> But it fails at the ExecuteScalar method, with an invalid operation
> exception.
If you are on SQL 2005 and use ADO .Net 2.0, you can enable MARS.
However, as Alan points out, you are probably barking up the wrong
tree. Calling back to the server for every row you get, does not
bode well for performance. You should try to get that scalar with
the first result set.
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

Monday, March 19, 2012

ExecuteReader Command

I am currently developing an asp.net application that uses sql server 2000.
In addition, I am also using the sql application data block provide off of
Microsoft's website.
My connection string to the database is stored in the Web.config file so
that it can be accessed by all classes. The connection string does not
contain any user name and password. The problem I am encountering is that I
cannot access the same connection string in the Web.config file within the
same method. I get a security exception saying the operation is not allowed
by the security policy. But it works the first time I use ExecuteReader but
not the second time.
Example:
Dim dr1 As SqlDataReader
dr1 = SqlHelper.ExecuteReader(ConfigurationSettings.AppSettings(...), ...)
While dr.Read()
..
Dim dr2 As SqlDataReader
dr2 = SqlHelper.ExecuteReader(ConfigurationSettings.AppSettings(...), ...)
..
End While
where ConfigurationSettings.AppSettings(...) is the connection string in my
Web.config file.
The error occurs the second time I call ExecuteReader using the connection
string in the Web.config file. HOWEVER, if instead of accessing the
connection string in Web.config, I hardcode the string with a user name and
password, then it works fine. But it doesn't work using the connection
string in Web.config file.
Any ideas?
Any help is appreciated.
Thanks.Hi James,
I don't kknow why this would happen but
Instead of doing that way , do this
Dim _ConnectionString as String =ConfigurationSettings.AppSettings(...)
Dim dr1 As SqlDataReader
dr1 = SqlHelper.ExecuteReader(_ConnectionString, ...)
...
...
and then just use the _ConnectionString Field. It will save on IO
Next . Don't use a datareader. It holds the connection open too long and
you can only open on datareader per connection. use a dataadapter and
dataset
Here is an example
Dim _SQLDataAdapter As New SqlClient.SqlDataAdapter("select co1,
col2 from table", _ConnectionString)
Dim _Dataset As New DataSet
Try
_SQLDataAdapter.Fill(_Dataset)
Catch ex As Exception
_Dataset = Nothing
End Try
If IsNothing(_Dataset) = False AndAlso _Dataset.Tables.Count = 0
Then
For Each _Datarow As DataRow In _Dataset.Tables(0).Rows
Response.Write(_Datarow.Item(0))
Next
Else
' write error message
End If
Now the SqlDataAdapter will open, execute, fill and close the connection in
one step. In this way you reduce the load on the SQL server
kind regards
Greg O
Need to document your databases. Use the first and still the best AGS SQL
Scribe
http://www.ag-software.com
"James" <James@.discussions.microsoft.com> wrote in message
news:AFE07474-3DEA-4EDD-96BA-D28CD595BB33@.microsoft.com...
>I am currently developing an asp.net application that uses sql server 2000.
> In addition, I am also using the sql application data block provide off of
> Microsoft's website.
> My connection string to the database is stored in the Web.config file so
> that it can be accessed by all classes. The connection string does not
> contain any user name and password. The problem I am encountering is that
> I
> cannot access the same connection string in the Web.config file within the
> same method. I get a security exception saying the operation is not
> allowed
> by the security policy. But it works the first time I use ExecuteReader
> but
> not the second time.
> Example:
> Dim dr1 As SqlDataReader
> dr1 = SqlHelper.ExecuteReader(ConfigurationSettings.AppSettings(...), ...)
> While dr.Read()
> ...
> Dim dr2 As SqlDataReader
> dr2 = SqlHelper.ExecuteReader(ConfigurationSettings.AppSettings(...),
> ...)
> ...
> End While
> where ConfigurationSettings.AppSettings(...) is the connection string in
> my
> Web.config file.
> The error occurs the second time I call ExecuteReader using the connection
> string in the Web.config file. HOWEVER, if instead of accessing the
> connection string in Web.config, I hardcode the string with a user name
> and
> password, then it works fine. But it doesn't work using the connection
> string in Web.config file.
> Any ideas?
> Any help is appreciated.
> Thanks.|||Thanks for the reply GregO.
I think I have narrowed down my problem. It has to do with a security
policy setting on IIS and/or .NET, I believe. Basically, if the two
ExecuteReaders use the connection string without the login information for
the database, the security exception occurs. If either one, or both,
ExecuteReaders use a connection string that includes the login information,
then it works fine. I haven't had a chance to look into this further but an
y
ideas?
As for the suggestion on not using the sqldatareader, this was my
alternative if I couldn't resolve the above issue. Thanks for the heads up.
One question does come to mind though. Would it be more expensive to use a
sqldatareader and open a connection and close it right away or use a
sqldataadapter and dataset and waste memory?
James
"GregO" wrote:

> Hi James,
> I don't kknow why this would happen but
> Instead of doing that way , do this
> Dim _ConnectionString as String =ConfigurationSettings.AppSettings(...)
> Dim dr1 As SqlDataReader
> dr1 = SqlHelper.ExecuteReader(_ConnectionString, ...)
> ...
> ...
>
> and then just use the _ConnectionString Field. It will save on IO
> Next . Don't use a datareader. It holds the connection open too long and
> you can only open on datareader per connection. use a dataadapter and
> dataset
> Here is an example
> Dim _SQLDataAdapter As New SqlClient.SqlDataAdapter("select co1,
> col2 from table", _ConnectionString)
> Dim _Dataset As New DataSet
> Try
> _SQLDataAdapter.Fill(_Dataset)
> Catch ex As Exception
> _Dataset = Nothing
> End Try
> If IsNothing(_Dataset) = False AndAlso _Dataset.Tables.Count = 0
> Then
> For Each _Datarow As DataRow In _Dataset.Tables(0).Rows
> Response.Write(_Datarow.Item(0))
> Next
> Else
> ' write error message
> End If
> Now the SqlDataAdapter will open, execute, fill and close the connection i
n
> one step. In this way you reduce the load on the SQL server
>
> --
> kind regards
> Greg O
> Need to document your databases. Use the first and still the best AGS SQL
> Scribe
> http://www.ag-software.com
> "James" <James@.discussions.microsoft.com> wrote in message
> news:AFE07474-3DEA-4EDD-96BA-D28CD595BB33@.microsoft.com...
>
>|||Just a couple of things to keep in mind:
1) The dataadapter uses a datareader "under the hood" to perform Fill
operations on a dataset or datatable, so there is no real performance
advantage to choosing a dataadapter. This is true as of version 1.1 - I have
not looked into the 2.0 library yet.
2) ConfigurationSettings uses a data cache when it retrieves data from the
web.config file, so multiple requests for the same item will not require
multiple file IO operations.
To get an idea on how the .NET framework classes perform their work, I
ecommend getting a free copy of Lutz Roeder's Reflector tool
(http://www.aisto.com/roeder/dotnet/). It is indispensible as a learning
tool.
"James" <James@.discussions.microsoft.com> wrote in message
news:AF3FDDD8-D514-41F9-999A-E156914A306F@.microsoft.com...
> Thanks for the reply GregO.
> I think I have narrowed down my problem. It has to do with a security
> policy setting on IIS and/or .NET, I believe. Basically, if the two
> ExecuteReaders use the connection string without the login information for
> the database, the security exception occurs. If either one, or both,
> ExecuteReaders use a connection string that includes the login
information,
> then it works fine. I haven't had a chance to look into this further but
any
> ideas?
> As for the suggestion on not using the sqldatareader, this was my
> alternative if I couldn't resolve the above issue. Thanks for the heads
up.
> One question does come to mind though. Would it be more expensive to use
a
> sqldatareader and open a connection and close it right away or use a
> sqldataadapter and dataset and waste memory?
> James
> "GregO" wrote:
>
and
in
SQL
2000.
off of
so
not
that
the
ExecuteReader
...)
SqlHelper.ExecuteReader(ConfigurationSettings.AppSettings(...),
in
connection
name
connection|||Hi Jeremy,
1) The performance increase isn't from using the datareader or not but on
how you use it. Typically what people do is loop through the reader doing
formatting and string stuff (Which is fine) . But what you need to remember
is that the connection is open to the database and if (as in web appliction)
you have 100's of users then this can mean hundreds of open connections.
Where as using a dataadapter adn the fill method you get a populate
dataset/datatable which you can loop through as much as you want but the
connection to the database is closed when you do this (unless you have
opened the connection manually). Now openning and closing the connection to
the database as quickly as possible is the best way of handling databsae
connections for scalabity and therefore performance. As I understand it
version still uses the datareader
2) Cached or not its alway better to plac the results of any function into a
local field if you are referencing that value multiple times. As appsetting
is a function it still performs steps and logic (cached or not) I agree you
wouldn't have the IO which is the main perfromance gain
kind regards
Greg O
Need to document your databases. Use the first and still the best AGS SQL
Scribe
http://www.ag-software.com
"Jeremy Williams" <jeremydwill@.netscape.net> wrote in message
news:up%23PJZPtFHA.2892@.TK2MSFTNGP10.phx.gbl...
> Just a couple of things to keep in mind:
> 1) The dataadapter uses a datareader "under the hood" to perform Fill
> operations on a dataset or datatable, so there is no real performance
> advantage to choosing a dataadapter. This is true as of version 1.1 - I
> have
> not looked into the 2.0 library yet.
> 2) ConfigurationSettings uses a data cache when it retrieves data from the
> web.config file, so multiple requests for the same item will not require
> multiple file IO operations.
> To get an idea on how the .NET framework classes perform their work, I
> ecommend getting a free copy of Lutz Roeder's Reflector tool
> (http://www.aisto.com/roeder/dotnet/). It is indispensible as a learning
> tool.
> "James" <James@.discussions.microsoft.com> wrote in message
> news:AF3FDDD8-D514-41F9-999A-E156914A306F@.microsoft.com...
> information,
> any
> up.
> a
> and
> in
> SQL
> 2000.
> off of
> so
> not
> that
> the
> ExecuteReader
> ...)
> SqlHelper.ExecuteReader(ConfigurationSettings.AppSettings(...),
> in
> connection
> name
> connection
>|||Hi Greg,
My main goal was simply to provide some context to the points you originally
made. If taken at face value, some people might have gotten the wrong
impression about how the DataReader and ConfigurationSettings classes work:
"...It will save on IO..."
"...It holds the connection open too long and you can only open on
datareader per connection..."
As for your most recent response:
1) Yes, I was referring to "equivalent" operations (filling a
dataset/datatable compared to creating custom objects based on the
datareader). In fact, depending on the simplicity of the custom data
objects, it might even be faster than filling a datatable/dataset, since
there is a fair amount of work involved in that process. The DataReader
itself, however, does not hold the connection open too long. That was my
point here.
2) I think Martin Fowler et al. might disagree with the unequivocal tone
(see 'Replace Temp with Query' from his book "Refactoring Improving the
Design of Existing Code"). From a purely performance-minded perspective, it
will most likely be quicker to access the value from a temp variable than it
would be to call the AppSettings method each time the value is needed, but
temp variables can sometimes have an effect on method structure that leads
to an overall degradation of performance (although usually only slightly).
And raw performance is not typically the only consideration in most
projects. Be that as it may, my main point here was to address the statement
about IO, and we both seem to agree there.
Thanks for the feedback and have a great wend!
"GregO" <grego@.community.nospam> wrote in message
news:%23SZHHhPtFHA.256@.tk2msftngp13.phx.gbl...
> Hi Jeremy,
> 1) The performance increase isn't from using the datareader or not but on
> how you use it. Typically what people do is loop through the reader doing
> formatting and string stuff (Which is fine) . But what you need to
> remember is that the connection is open to the database and if (as in web
> appliction) you have 100's of users then this can mean hundreds of open
> connections. Where as using a dataadapter adn the fill method you get a
> populate dataset/datatable which you can loop through as much as you want
> but the connection to the database is closed when you do this (unless you
> have opened the connection manually). Now openning and closing the
> connection to the database as quickly as possible is the best way of
> handling databsae connections for scalabity and therefore performance. As
> I understand it version still uses the datareader
> 2) Cached or not its alway better to plac the results of any function into
> a local field if you are referencing that value multiple times. As
> appsetting is a function it still performs steps and logic (cached or not)
> I agree you wouldn't have the IO which is the main perfromance gain
>
> --
> kind regards
> Greg O
> Need to document your databases. Use the first and still the best AGS SQL
> Scribe
> http://www.ag-software.com
> "Jeremy Williams" <jeremydwill@.netscape.net> wrote in message
> news:up%23PJZPtFHA.2892@.TK2MSFTNGP10.phx.gbl...
>|||Hey that's alright. It's good to have these discussions.
kind regards
Greg O
Need to document your databases. Use the first and still the best AGS SQL
Scribe
http://www.ag-software.com
"Jeremy Williams" <jeremydwill@.netscape.net> wrote in message
news:OZZe87VtFHA.3264@.TK2MSFTNGP12.phx.gbl...
> Hi Greg,
> My main goal was simply to provide some context to the points you
> originally made. If taken at face value, some people might have gotten the
> wrong impression about how the DataReader and ConfigurationSettings
> classes work:
> "...It will save on IO..."
> "...It holds the connection open too long and you can only open on
> datareader per connection..."
> As for your most recent response:
> 1) Yes, I was referring to "equivalent" operations (filling a
> dataset/datatable compared to creating custom objects based on the
> datareader). In fact, depending on the simplicity of the custom data
> objects, it might even be faster than filling a datatable/dataset, since
> there is a fair amount of work involved in that process. The DataReader
> itself, however, does not hold the connection open too long. That was my
> point here.
> 2) I think Martin Fowler et al. might disagree with the unequivocal tone
> (see 'Replace Temp with Query' from his book "Refactoring Improving the
> Design of Existing Code"). From a purely performance-minded perspective,
> it will most likely be quicker to access the value from a temp variable
> than it would be to call the AppSettings method each time the value is
> needed, but temp variables can sometimes have an effect on method
> structure that leads to an overall degradation of performance (although
> usually only slightly). And raw performance is not typically the only
> consideration in most projects. Be that as it may, my main point here was
> to address the statement about IO, and we both seem to agree there.
> Thanks for the feedback and have a great wend!
> "GregO" <grego@.community.nospam> wrote in message
> news:%23SZHHhPtFHA.256@.tk2msftngp13.phx.gbl...
>

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 for sql2005

I hope you would help me in this problem. I use the code below for executenonquery command for mdb DB.But I do not know the changes I should made when Using SQL2005.

----
Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0; " & _
"Data Source=C:\ASPNET20\data\Northwind.mdb"
Dim dbConnection As New OleDbConnection(connectionString)
dbConnection.Open()

Dim commandString As String = "INSERT INTO Employees(FirstName, LastName) " & _
"Values(@.FirstName, @.LastName)"

Dim dbCommand As New OleDbCommand(commandString, dbConnection)

Dim firstNameParam As New OleDbParameter("@.FirstName", OleDbType.VarChar, 10)
firstNameParam.Value = txtFirstName.Text
dbCommand.Parameters.Add(firstNameParam)

Dim lastNameParam As New OleDbParameter("@.LastName", OleDbType.VarChar, 20)
LastNameParam.Value = txtLastName.Text
dbCommand.Parameters.Add(LastNameParam)

dbCommand.ExecuteNonQuery()

dbConnection.Close()
---

You can check SqlCommand class. You can take a look at this link:

http://msdn2.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters.aspx

|||Search "Ole" and replace with "Sql"

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.

Monday, March 12, 2012

execute stored procedure (with parameters) with an "exec" command

Hi everybody, I would like to know if it's possible to execute a stored procedure, passing it parameters, using not CommandType.StoredProcedure value of sqlcommand, but CommandType.Text.

I tried to use this:
sqlCmd.CommandType = CommandType.Text
sqlCmd.Parameters.Add(sqlPar)
sqlCmd.ExecuteNonQuery()

With this sql command:
"exec sp ..."

I wasn't able to make it to work, and I don't know if it's possible.

Another question:
if it's not possible, how can I pass a Null value to stored procedure?
This code:
sqlPar = new SqlParameter("@.id", SqlDbType.Int)
sqlPar.Direction = ParameterDirection.Output
cmd.Parameters.Add(sqlPar)

sqlPar = new SqlParameter("@.parent_id", DBNull)
cmd.Parameters.Add(sqlPar)

doesn't work, 'cause I get this error:
BC30684: 'DBNull' is a type and cannot be used as an expression.

How can I solve this?
Bye and thanks in advance.

P.S. I would prefer first method to call a stored procedure ('cause I could call it with 'exec sp null' sql command, solving the other problem), but obviusly if it's possible...=)

Sorry for grammatical mistakes.It's DBNull.Value|||Try:

sqlPar = new SqlParameter("@.parent_id", DBNull.Value)|||Perfect, it works, but now I have another problem.
I get this error:
This SqlTransaction has completed; it is no longer usable.

When I run Commit or Rollback code.|||Are you committing the transaction twice accidentally?|||No, I'm sure.
The only "strange" thing I do it's to call 2 different functions in my class to begin and commit/rollback transaction.|||Then you will have to show some code...|||'CConn is my class
CConn.BeginTransaction()

Dim arParameters as new ArrayList()

Dim sqlParOutput = new SqlParameter("@.id", SqlDbType.Int)
sqlParOutput.Direction = ParameterDirection.Output
arParameters.Add(sqlParOutput)

Dim sqlPar = new SqlParameter("@.parent_id", DBNull.Value)
arParameters.Add(sqlPar)

objTransaction = CConn.ExecuteNonQuery("sp", arParameters, false)

if objTransaction is nothing then objTransaction = CConn.ExecuteNonQuery("...")

if objTransaction is nothing then
CConn.CommitTransaction()
else
CConn.RollbackTransaction()
end if

The Begin, Commit and Rollback functions in CConn class simply call the same functions of SqlConnection object.
The ExecuteNonQuery function override standard function.|||This helps sort of not at all. We do not know what your class is doing. Is the return from CConn.ExecuteNonQuery a transaction object? What is the significance of objTransaction being nothing?|||Sorry, you're right.
Here the class methods:


Public function BeginTransaction() as SqlTransaction
Me.Conn = New SqlConnection(Me.sConnStr)
Me.Conn.Open()
'Start a local transaction
Me.myTransaction = Conn.BeginTransaction()
end function

Public sub CommitTransaction()
Me.myTransaction.Commit()
Me.Conn.Close()
end sub

Public function RollbackTransaction() 'transaction as SqlTransaction)
Me.myTransaction.Rollback()
Me.Conn.Close()
end function

Public function ExecuteNonQuery(ByVal SQL As String, optional sqlParameters as ArrayList = nothing, optional toClose as boolean = true) as object
Dim objReturn as object
if Me.Conn is nothing then
Me.Conn = New SqlConnection(Me.sConnStr)
Me.Conn.Open()
else
if Me.Conn.State <> ConnectionState.Open then Me.Conn.Open()
end if

Dim sqlCmd As New SqlCommand(SQL, Me.Conn)

'Must assign transaction object to Command object for a pending local transaction
if not Me.myTransaction is nothing then sqlCmd.Transaction = Me.myTransaction

Try
if not sqlParameters is nothing then
sqlCmd.CommandType = CommandType.StoredProcedure
Dim sqlPar as SqlParameter
for each sqlPar in sqlParameters
sqlCmd.Parameters.Add(sqlPar)
next
else
sqlCmd.CommandType = CommandType.Text
end if
sqlCmd.ExecuteNonQuery()
Catch e As Exception
objReturn = e
End Try

'must be clean up?
if toClose then
Me.Conn.Close()
sqlCmd.Dispose()
Me.Conn.Dispose()
end if

return objReturn
End function

Execute Statements in Order

Dear friends,
I am using query analyzer to build a database,
I want to do certain command in order, that is: not to execute the next statement until the previous one has been finish execution.
What is the command used for this purpose
Thanks for your valuable helpGO

The message I have entered is too short|||You don't even need the GO command. Sequential statements in a script execute sequentially anyway.|||You don't even need the GO command. Sequential statements in a script execute sequentially anyway.
unless there is no 'goto' statement|||You need a GO ...If you have sequential steps SL server will open multiple threads and execute it independent of each other....|||You need a GO ...If you have sequential steps SL server will open multiple threads and execute it independent of each other....I've never seen separate statements in a SQL batch executed out of order. I don't believe that is possible.

You can use IF...THEN...ELSE, WHILE, and RETURN to control flow, and there is still GOTO (which is rarely used), but otherwise the individual (atomic) SQL statements are executed in the order that they are specified. Within a given statement like a SELECT, different clauses can execute unpredictably (for example the JOINs can materialize in whatever order the database engine finds convenient), but the individual SQL statements are always executed in sequence as directed by the flow of control statements.

-PatP|||You need a GO ...If you have sequential steps SL server will open multiple threads and execute it independent of each other....
Absolultely not. TSQL is a procedural language.|||From originator,

Thansk for all, but,
I believe that the statments will start excute sequentially, but
for example if i have 3 statments, the first needs 4 minites to finish execute
the second and third needs only one second,
in this case the server will start excute the first statment, then the second ( before the first finishes) , then the third

why i think like this,

I have around 30 statments to import data from MS Access into MS SQL
when i excute the statments by marking command by command , then pressing F5. It works fine,
but when i excutes all at the same time , it will give errors...

I tried GO but still giving errors

Thanks again for effort.|||Can you post your script? I'm not sure what problem(s) you are finding, but I can guarantee you that the statements will be processed one at a time, in the order that they appear in the script (unless you have statements that explicitly change the flow of control such as IF...THEN...ELSE).

-PatP|||The Script is as follows:

select Schools

truncate table [Log] --
truncate table Course --
truncate table Exam --
truncate table Exam4 --
truncate table ExamDef --
truncate table Payment --
truncate table Permit --
truncate table Prohibit --
truncate table SecTopicSub2 --
truncate table Student --
truncate table Groups --
truncate table DailyTransaction --
truncate table reGrouping --
truncate table rePayment --
truncate table SalesVoucher --

truncate table AccRestrict -- should keep some users
truncate table SecTopicSub -- should keep some users
truncate table SPass -- should keep some users
truncate table City
truncate table Nationality
truncate table Sales
truncate table CourseT
truncate table Classify
truncate table ClassRoom
truncate table Period
truncate table PermitNo
truncate table Reference
truncate table Remarks
truncate table [Static]
truncate table StaticB
truncate table Stations
truncate table Trade
truncate table SS1_Locked_Records

go

INSERT INTO AccRestrict (Code,User1,access) SELECT * FROM
OPENROWSET('msdasql', 'DRIVER=Microsoft Access Driver (*.mdb);pwd=avonlea;DBQ=c:\temp\SchoolR.mdb',
'SELECT Code,User1,access from AccRestrict') as aa

INSERT INTO City (Code,Desc1) SELECT * FROM
OPENROWSET('msdasql', 'DRIVER=Microsoft Access Driver (*.mdb);pwd=avonlea;DBQ=c:\temp\SchoolR.mdb',
'SELECT Code,Desc1 from City') as aa

INSERT INTO Classify (Class,Desc1) SELECT * FROM
OPENROWSET('msdasql', 'DRIVER=Microsoft Access Driver (*.mdb);pwd=avonlea;DBQ=c:\temp\SchoolR.mdb',
'SELECT Class, Desc1 from Classify ') as aa

go

INSERT INTO ClassRoom (ClassNo,Seats,Desc1) SELECT * FROM
OPENROWSET('msdasql', 'DRIVER=Microsoft Access Driver (*.mdb);pwd=avonlea;DBQ=c:\temp\SchoolR.mdb',
'SELECT ClassNo,Seats,Desc1 from ClassRoom ') as aa

INSERT INTO Course (CourseID,CourseT, CourseNo, CName, StartG,StartH, EndG ,EndH ,
Period, FromTime, ToTime,Open1,
EnterResult, Periods, Max1, Current1, Days, AllowAbs, Amount, Station, User1,
School, ClassRoom,Limit1,Limit2,Limit3,Limit4,Limit5,Regis ter1,Register2,Register3,Register4,Register5,
DateSG1,DateSG2,DateSG3,DateSG4,DateSG7,DateSH1,Da teSH2,DateSH3,DateSH4,DateSH7)
SELECT * FROM
OPENROWSET('msdasql', 'DRIVER=Microsoft Access Driver (*.mdb);pwd=avonlea;DBQ=c:\temp\SchoolR.mdb',
'SELECT CourseID,CourseT, CourseNo, CName, StartG,Str(StartH), EndG ,Str(EndH) ,Period, FromTime, ToTime,Open1,
EnterResult, Periods, Max1, Current1, Days, AllowAbs, Amount, Station, User1,
School, ClassRoom,Limit1,Limit2,Limit3,Limit4,Limit5,Regis ter1,Register2,Register3,Register4,Register5,
DateSG1,DateSG2,DateSG3,DateSG4,DateSG7,Str(DateSH 1),Str(DateSH2), Str(DateSH3),Str(DateSH4), Str(DateSH7)
from Course') as aa

------------------

INSERT INTO CourseT (CourseT, CName,Amount,Type1, Type2, PrintForm, Active, Remarks,
Days,Periods, AllowAbs, Class, ExamSort, StatSort, StatSortB, User1, StudList, Min_Age,
AllowDaysDistribution ) SELECT * FROM
OPENROWSET('msdasql', 'DRIVER=Microsoft Access Driver (*.mdb);pwd=avonlea;DBQ=c:\temp\SchoolR.mdb',
'SELECT CourseT, CName,Amount,Type1, Type2, PrintForm, Active, Remarks,
Days,Periods, AllowAbs, Class, ExamSort, StatSort, StatSortB, User1, StudList, Min_Age,
AllowDaysDistribution from CourseT ') as aa
go
------------------
--truncate table exam
INSERT INTO Exam (StudID,Course,ExNo, ReExam, DateG, DateH ,Result, Result1, Result2, Result3,
Remarks, Station, User1, School, Sno)
SELECT * FROM
OPENROWSET('msdasql', 'DRIVER=Microsoft Access Driver (*.mdb);pwd=avonlea;DBQ=c:\temp\SchoolR.mdb',
'Select StudID,Course,ExNo, ReExam, iif(DateG>#01/01/1990# and DateG<#01/01/2010#, DateG ,null) as DateG1 ,
left(str(DateH),10) as DateH1 ,Result, Result1, Result2, Result3,
Remarks, Station, User1, School, Sno from Exam where SNo <> 33759085') as aa
go
-- select Top 20000 * from exam
Update Exam set dateh = '0'+DateH where substring(DateH,2,1)='/'
Update Exam set dateh = left(DateH,3)+'0'+substring(DateH,4,6) where substring(DateH,5,1)='/'
update exam set DateH = Substring(DateH,4,2) + '/' + left(dateh,2) + '/' + substring(dateH,7,4) where substring(DateH,4,2) > '12'

-- where SNo <> 33759085 ') as aa -- for Jizan only
------------------

set IDENTITY_INSERT Exam4 On
go

INSERT INTO Exam4 ([ID], StudID, Course, ExNo, DateG, DateH, ExpiryG, Expire, PermitID, Remarks, Address, Tel)
SELECT * FROM
OPENROWSET('msdasql', 'DRIVER=Microsoft Access Driver (*.mdb);pwd=avonlea;DBQ=c:\temp\SchoolR.mdb',
'select ID, StudID, Course, ExNo, DateG, Str(DateH), ExpiryG, Expire, PermitID, Remarks, Address, Tel
from exam4') as aa
set IDENTITY_INSERT Exam4 off
------------------
go

INSERT INTO ExamDef (ExamNo,DateG, DateH, MaxNorm, MaxFail, CurrNorm, CurrFail, Status)
SELECT * FROM
OPENROWSET('msdasql', 'DRIVER=Microsoft Access Driver (*.mdb);pwd=avonlea;DBQ=c:\temp\SchoolR.mdb',
'select ExamNo,iif(DateG<#01/01/1900#,#01/01/1900#, DateG), Str(DateH), MaxNorm, MaxFail,
CurrNorm, CurrFail, Status from ExamDef') as aa

------------------

INSERT INTO Nationality (Code,Desc1) SELECT * FROM
OPENROWSET('msdasql', 'DRIVER=Microsoft Access Driver (*.mdb);pwd=avonlea;DBQ=c:\temp\SchoolR.mdb',
'SELECT Code,Desc1 from Nationality') as aa

go

-------------------
set IDENTITY_INSERT Payment On
-------------------

INSERT INTO Payment (PayNo, PayDateG, PayDateH,PayType,StudID,Course ,Amount,Result, Absence,
Group1, Printed ,DialogPrinted, OldPay,
OldSchool, WithDraw ,Station ,User1,Copied, School, Sno,CStartDay,List)
SELECT * FROM
OPENROWSET('msdasql', 'DRIVER=Microsoft Access Driver (*.mdb);pwd=avonlea;DBQ=c:\temp\SchoolR.mdb',
'select PayNo, IIF(PayDateG<#01/01/1900#,#01/01/1900#,PayDateG) as PayDateG1,
left(Str(PayDateH),10) as PayDateH1,PayType,StudID,Course ,Amount,Result,
Absence, Group1, Printed ,DialogPrinted, OldPay,
OldSchool, WithDraw ,Station ,User1,Copied, School, Sno, CStartDay,List
FROM [payment]') AS aa where Len(PayDateH1)<=10 -- this last where is for Jizan = keep this since no need to such record (empty)

-------------------
set IDENTITY_INSERT Payment Off
go

------------------

------------------

INSERT INTO SecTopicSub SELECT * FROM
OPENROWSET('msdasql', 'DRIVER=Microsoft Access Driver (*.mdb);pwd=avonlea;DBQ=c:\temp\SchoolR.mdb',
'select * FROM SecTopicSub ') AS aa

INSERT INTO SecTopicSub2 SELECT * FROM
OPENROWSET('msdasql', 'DRIVER=Microsoft Access Driver (*.mdb);pwd=avonlea;DBQ=c:\temp\SchoolR.mdb',
'select * FROM SecTopicSub2 ') AS aa

INSERT INTO Spass (user1,UserName, access, [password], lastpchanged,
logged, [time], AutoList, IDFirst, AddMode, CourseFilter1, DialogPrint )
SELECT * FROM
OPENROWSET('msdasql', 'DRIVER=Microsoft Access Driver (*.mdb);pwd=avonlea;DBQ=c:\temp\SchoolR.mdb',
'select user1,UserName, access, [password], lastpchanged,
logged, [time], AutoList, IDFirst, AddMode, CourseFilter1, DialogPrint FROM Spass ') AS aa

go

INSERT INTO Static SELECT * FROM
OPENROWSET('msdasql', 'DRIVER=Microsoft Access Driver (*.mdb);pwd=avonlea;DBQ=c:\temp\SchoolR.mdb',
'select * FROM Static ') AS aa

INSERT INTO StaticB SELECT * FROM
OPENROWSET('msdasql', 'DRIVER=Microsoft Access Driver (*.mdb);pwd=avonlea;DBQ=c:\temp\SchoolR.mdb',
'select * FROM StaticB ') AS aa

INSERT INTO Stations (Code,Desc1,PrinterTop1) SELECT * FROM
OPENROWSET('msdasql', 'DRIVER=Microsoft Access Driver (*.mdb);pwd=avonlea;DBQ=c:\temp\SchoolR.mdb',
'select Code,Desc1, iif(PrinterTop1<0,0,PrinterTop1) FROM Stations ') AS aa

------------------
--select * from stations
go

INSERT INTO groups SELECT * FROM
OPENROWSET('msdasql', 'DRIVER=Microsoft Access Driver (*.mdb);pwd=avonlea;DBQ=c:\temp\SchoolR.mdb',
'select * FROM groups') AS aa

go

set IDENTITY_INSERT DailyTransaction On

INSERT INTO DailyTransaction (SNo,[Date],Amount,Posted,Batch) SELECT * FROM
OPENROWSET('msdasql', 'DRIVER=Microsoft Access Driver (*.mdb);pwd=avonlea;DBQ=c:\temp\SchoolR.mdb',
'select * FROM DailyTransaction') AS aa

set IDENTITY_INSERT DailyTransaction Off

go

INSERT INTO reGrouping SELECT * FROM
OPENROWSET('msdasql', 'DRIVER=Microsoft Access Driver (*.mdb);pwd=avonlea;DBQ=c:\temp\SchoolR.mdb',
'select * FROM reGrouping') AS aa

go

set IDENTITY_INSERT rePayment On

INSERT INTO rePayment (NewPayNo, PayDateG,PayDateH,StudID,Amount,Station,User1, Course,CName,
PayType, PayNo,OldPay,OldSchool) SELECT * FROM
OPENROWSET('msdasql', 'DRIVER=Microsoft Access Driver (*.mdb);pwd=avonlea;DBQ=c:\temp\SchoolR.mdb',
'select NewPayNo, PayDateG,Str(PayDateH),StudID,Amount,Station,User1 , Course,CName,
PayType, PayNo,OldPay,OldSchool FROM rePayment') AS aa

set IDENTITY_INSERT rePayment Off

Go|||First observation, TRUNCATE TABLE is a complete wipe of the table... Nothing is ever left in a truncated table.

What kind of errors are you getting, and where are you getting them? The rest of this script looks Ok at least from a simple look.

-PatP|||after i implement GO, there was one problem, but i correct and the transaction works fine ,
thanks for help.

Ridwan|||how to close this Thread?|||I'm glad that you were able to find and fix your problem.

If implementing the GO between statements makes you happy, that's good, but it was definitely not part of your solution. While the use of the GO statements would not hurt anything, they would not help either, so removing those GO statements from your corrected script wouldn't change anything. There are a few SQL statements that must be the first or only statement in a batch (so they require the use of GO), but none of them are used in the script that you posted.

We don't normally close threads here at DBForums. It can be done, but it is pointless in nearly all cases.

-PatP

Execute SQL Task with no rows affected

Hi,

I used with Execute SQL Task for update a table in Oracle DB.

I saw that when the command has no rows for updeting, the task fails.

Here is my command:

update tableName set fieldA=sysdate where fieldB is Null

and again, when there are some rows that fieldB is Null then the command succeed, but when the fieldB in all the rows is not null the command fails.

I tried to play with the ResultSet with no success.

Please your advice.

Thank you in advance

Noam

What error or errors are returned when the task fails? Can you please copy and paste the error output from BIDS or from a log file into a reply?

Are you attempting to store the resultset from the query in a variable?

Can you run the query successfully (where zero rows are affected) without error using SQL*Plus or another query tool?

This information will likely be invaluable in helping track down the source of the error.

|||

Thank you for your reply.

This is the error:

"Error: 0xC002F210 at Execute SQL Task, Execute SQL Task: Executing the query "update TableName set FieldA=SYSDATE where FieldB is Null" failed with the following error: "Error HRESULT E_FAIL has been returned from a call to a COM component.". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.
Task failed: Execute SQL Task
."

No, I didn't attempt to store the resultset, I just executed the query.

and yes, I ran the query successfully using SQL*Plus with the result : "0 rows updated."

Please your help.

Thanks

Noam

|||

I found it.

My connection was odbc.

I changed the connection to Ado.Net provider for odbc and it works without fail.

Why?

It's another question.

Thank you anyway.

Noam

Friday, March 9, 2012

Execute SQL Task passing parameters to a restore command

Hi,

I'm very new to SSIS and I’m trying to do the following in a SQL task

RESTORE DATABASE @.DatabaseName FROM DISK = @.Backup WITH FILE = 1, MOVE @.OldMDFName TO @.NewMDFPath, MOVE @.OldLDFName TO @.NewLDFPath, NOUNLOAD, REPLACE, STATS = 10

I'm using an OLE DB connection and I have mapped user variables to the various parameter names. Unfortunately when i test the above command it fails on must declare the scalar variable "@.DatabaseName". How can i get my values to be substituted into the command?

Many thanks

Martin

The best way is to build your SQL statement in a variable via expressions and then use that variable as the SQL source for the Execute SQL task.|||I don't think you can parameterize a RESTORE DATABASE command like that.

The way I'd do it is to create a new parameter named SqlStatement or something of similar meaning. This parameter's EvaluateAsExpression property will be True and the Expression property will be: "RESTORE DATABASE " + @.[User::DatabaseName] + " FROM DISK = ...". Then set the SQLSourceType of your Execute SQL Task to Variable and specify SqlStatement as the variable.

Wednesday, March 7, 2012

execute sql server agent job task - Job immediately returns success... However agent job is

when I run a package from a command window using dtexec, the job immediately says success.

DTExec: The package execution returned DTSER_SUCCESS (0).

Started:3:37:41 PM

Finished: 3:37:43 PM

Elapsed:2.719 seconds

However the Job is still in th agent and the status is executing. The implications of this are not good. Is this how the sql server agent job task is supposed to work by design.

Thanks,

Larry

Just to get this right. Your SSIS package starts a SQL Agent job. You are executing the package and it completes immediately. This is by design. There is no synchronous hook into the SQL Agent Job Scheduling, you can implement a waiting loop to check the job has completed but that is quite messy.

Execute SQL dynamically

Hi,
I want to execute some SQL statement that has more than 4000 characters, is
there any way to do it?
I'm using the exec sp_executesql command as following:
declare @.SQLString nvarchar(4000)
select @.SQLString = 'SQL statement more than 4000 characters'
exec sp_executesql @.SQLString
ThanksFerreira wrote:

> Hi,
> I want to execute some SQL statement that has more than 4000 characters, i
s
> there any way to do it?
> I'm using the exec sp_executesql command as following:
> declare @.SQLString nvarchar(4000)
> select @.SQLString = 'SQL statement more than 4000 characters'
> exec sp_executesql @.SQLString
> Thanks
declare @.var1 navarchar(4000)
declare @.var2 navarchar(4000)
set @.var1 = 'bla bla ..................'
set @.var2 = 'aaaabbbb ...............'
exec (@.var1 + @.var2)
Regards
Amish Shah|||http://www.sommarskog.se/dynamic_sql.html
Madhivanan
amish wrote:
> Ferreira wrote:
>
> declare @.var1 navarchar(4000)
> declare @.var2 navarchar(4000)
> set @.var1 = 'bla bla ..................'
> set @.var2 = 'aaaabbbb ...............'
> exec (@.var1 + @.var2)
> Regards
> Amish Shah|||Ferreira (Ferreira@.discussions.microsoft.com) writes:
> I want to execute some SQL statement that has more than 4000 characters,
> is there any way to do it? > I'm using the exec sp_executesql command as
> following:
> declare @.SQLString nvarchar(4000)
> select @.SQLString = 'SQL statement more than 4000 characters'
> exec sp_executesql @.SQLString
In addition to the other posts, note that if you are on SQL 2005, you can
use the new data type nvarchar(MAX) instead. This data type is unlimited
like ntext, but does not have all the restrictions of ntext.
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

Sunday, February 26, 2012

Execute Process Task using StandardInputVariable

Greetings!

I am using a Excute Process Task calling a selfwritten EXE and I'm trying to pass a command line argument to it. The code for the EXE is quit simple:

Public Sub Main()
Try
Dim info As String = My.Application.CommandLineArgs.Item(0)
MessageBox.Show("Info:" & info)
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
End Sub

According to the help files there are two ways to pass an argument, using the property Arguments, which I guess is for hard-coded stuff, and the StandardInputVariable for passing dynamic info.

When I use the Arguments property everything works fine. I get the info messagebox with correct data. But when I leave that blank and instead use the StandardInputVariable property setting it to my package variable User::Info then I crash into an exception meaning that no arguments existed (array is out of bonds).

The variable User::Info was at first filled from a previous SSIS task and using the OnPreExecute breakpoint I verified that it contained a stringvalue. I then hardcoded a string value into the variable, but nothing helps. The task refuses to start my EXE with the data in the StandardInputVariable as an argument.

Why is this not working?

When you use the StandardInputVariable property setting, are you declaring the StandardInputVariable property in the code for the EXE?|||

I am not sure what you mean by this. The StandardInputVariable is just a property in the SSIS task Execute Process. It's supposed to just pass the content of the selected variable as a start-up argument to the selected EXE. Is there some kind of a global variable inside my VS2005 VB project that automatically gets some info that is not passed as an argument? Or can I declare something like that?

All my EXE file should need to do is look at the arguments (the first only in this case) passed to it like this:

Dim arg as string = My.Application.CommandLineArgs.Item(0)

If i use the Argument propert it works fine. But that is for hard coded start-up values like standard /H for help or /Q for quiet. I need to pass a dynamic value and that's what StandardInputVariable is for. I have verified that my SSIS variable contains the correct data. Yet no argument is delivered to the EXE file.

|||

Use an expression on the Arguments property for passing both static and dynamic command line arguments to an execute process task.

By using an expression, you can incorporate any combination. For example, the expression on Arguments could be: "/Q" + @.User::FilePath

The StandardInputVariable is a task property pointing to a variable who's contents will be streamed in on the process' standard input file handle. If you log the Execute Process specific event entitled "ExecuteProcessVariableRouting", and make use of the StandardInputVariable task property, note that that the log message says, "Routing stdin from variable "User:<your variable here>".

|||

It turns out that you need to include a call to Console.Readline, as follows:

Dim info As String = Console.Readline

And, of course, make sure that the StandardInputVariable property is set to the package variable containing the value you want to pass. I also left the Auguments property setting blank when I tested this procedure.

Carla

|||

Thank you very much. This solved the problem.

I never thought of using Console since my application is a Windows Forms executable, but it worked like a charm.

|||

Please!

Is it possible to link two o more system variables (StartTime + UserName) in a user variable?

I tried Name=User::MyVar and Value=System::StartTime + "Test" but when I try to read by using your

Dim Info As String = Console.ReadLine

it give me the string "System::StartTime + "Test""

Thanks in advance.

Alex.|||

Not sure if I completely understand your question, but it sounds like you need to use an expression for your variable. You can do this by setting the EvaluateAsExpression property of the variable to TRUE, and then enter your expression (i.e., User::MyVar + User::MyVar2) into the Expression property.

You may need to cast the variables to concatenate them. The expression builder will help you validate that the expression is correct.

Execute Process Task using StandardInputVariable

Greetings!

I am using a Excute Process Task calling a selfwritten EXE and I'm trying to pass a command line argument to it. The code for the EXE is quit simple:

Public Sub Main()
Try
Dim info As String = My.Application.CommandLineArgs.Item(0)
MessageBox.Show("Info:" & info)
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
End Sub

According to the help files there are two ways to pass an argument, using the property Arguments, which I guess is for hard-coded stuff, and the StandardInputVariable for passing dynamic info.

When I use the Arguments property everything works fine. I get the info messagebox with correct data. But when I leave that blank and instead use the StandardInputVariable property setting it to my package variable User::Info then I crash into an exception meaning that no arguments existed (array is out of bonds).

The variable User::Info was at first filled from a previous SSIS task and using the OnPreExecute breakpoint I verified that it contained a stringvalue. I then hardcoded a string value into the variable, but nothing helps. The task refuses to start my EXE with the data in the StandardInputVariable as an argument.

Why is this not working?

When you use the StandardInputVariable property setting, are you declaring the StandardInputVariable property in the code for the EXE?|||

I am not sure what you mean by this. The StandardInputVariable is just a property in the SSIS task Execute Process. It's supposed to just pass the content of the selected variable as a start-up argument to the selected EXE. Is there some kind of a global variable inside my VS2005 VB project that automatically gets some info that is not passed as an argument? Or can I declare something like that?

All my EXE file should need to do is look at the arguments (the first only in this case) passed to it like this:

Dim arg as string = My.Application.CommandLineArgs.Item(0)

If i use the Argument propert it works fine. But that is for hard coded start-up values like standard /H for help or /Q for quiet. I need to pass a dynamic value and that's what StandardInputVariable is for. I have verified that my SSIS variable contains the correct data. Yet no argument is delivered to the EXE file.

|||

Use an expression on the Arguments property for passing both static and dynamic command line arguments to an execute process task.

By using an expression, you can incorporate any combination. For example, the expression on Arguments could be: "/Q" + @.User::FilePath

The StandardInputVariable is a task property pointing to a variable who's contents will be streamed in on the process' standard input file handle. If you log the Execute Process specific event entitled "ExecuteProcessVariableRouting", and make use of the StandardInputVariable task property, note that that the log message says, "Routing stdin from variable "User:<your variable here>".

|||

It turns out that you need to include a call to Console.Readline, as follows:

Dim info As String = Console.Readline

And, of course, make sure that the StandardInputVariable property is set to the package variable containing the value you want to pass. I also left the Auguments property setting blank when I tested this procedure.

Carla

|||

Thank you very much. This solved the problem.

I never thought of using Console since my application is a Windows Forms executable, but it worked like a charm.

|||

Please!

Is it possible to link two o more system variables (StartTime + UserName) in a user variable?

I tried Name=User::MyVar and Value=System::StartTime + "Test" but when I try to read by using your

Dim Info As String = Console.ReadLine

it give me the string "System::StartTime + "Test""

Thanks in advance.

Alex.|||

Not sure if I completely understand your question, but it sounds like you need to use an expression for your variable. You can do this by setting the EvaluateAsExpression property of the variable to TRUE, and then enter your expression (i.e., User::MyVar + User::MyVar2) into the Expression property.

You may need to cast the variables to concatenate them. The expression builder will help you validate that the expression is correct.

Execute Process Task Error on copy

Hi,

I am trying to run a very simple copy command from an execute process task:

copy O:\myFolder\myFile*.txt D:\myFolder

I have a working directory set also.

However, there is an error icon on the task, and if I attempt to run it I get the following error:

Error at Execute Process Task [Execute Process Task]: File/Process "" does not exist in directory "copy O:\myFolder\myFile*.txt D:\myFolder".

Error at Execute Process Task: There were errors during task validation.

This command works fine from the command line. What am I doing wrong here?

Thanks


O:\myFolder\myFile*.txt D:\myFolder

The above should go in the arguments parameter box if you're not doing that.|||

It seems that it's looking for an executable, like a .bat file. It doesn't seem to recognize the dos copy command.

for example:

Executable: copy

Arguments: o:\myFolder\myFile.txt D:\myFolder

but it still complains that copy is not an executable.

So, it seems I have to put this in a batch file, which seems dumb, or I need to use the File System Task, but I don't know how to specify which files to copy using this method.

?

|||Instead, try using the full path to xcopy

c:\windows\xcopy.exe|||

xcopy is not installed

where can one find just the "copy" command exe?

|||

sadie519590 wrote:

xcopy is not installed

where can one find just the "copy" command exe?

xcopy is not installed? You're kidding me? Wink It's distributed with Windows.

There is no "copy.exe" as it's an internal command within "command.exe or cmd.exe."|||

Actually you are correct. I was thinking of robocopy.

At any rate, SSIS is complaining it can't find the xcopy exe. Never mind at this point, I'm not going to use it for now.

But for future use, it seems to me that there should be a way to use the File System task to specify file names with wildcards?

|||

sadie519590 wrote:

Actually you are correct. I was thinking of robocopy.

At any rate, SSIS is complaining it can't find the xcopy exe. Never mind at this point, I'm not going to use it for now.

But for future use, it seems to me that there should be a way to use the File System task to specify file names with wildcards?

You need to specify the full path to xcopy.exe in the Executable parameter..|||But I'm still wondering if I can use wild cards to specify files names in the File System Task when deleting files? Seems like this would be easier approach if possible.|||

sadie519590 wrote:

But I'm still wondering if I can use wild cards to specify files names in the File System Task when deleting files? Seems like this would be easier approach if possible.

I think the way to do this is to use a foreach loop to scan the source directory for the files you want to copy (you can use a wildcard there) and then have it populate some variables (source filename, etc...). Then, inside the foreach loop, you use a filesystem task to perform the operation for each file found by the foreach loop.

Does that make sense?|||Yes, thanks. I'm surprised there's no built-in way to do this. Product request, I guess?|||

sadie519590 wrote:

Yes, thanks. I'm surprised there's no built-in way to do this. Product request, I guess?

Sure thing! http://connect.microsoft.com/sqlserver/feedback