Failing To Execute Command Using Xp_CmdShell

Sep 28, 2001

Hi all,

In SQL Server using xp_cmdshell we can excute any of the command or executable files which can be executed in command prompt. Here my problem is that .. I am trying to execute OSQL from the MSSQL(Query Analyser) using xp_cmdshell.. but its give error saying "'osql' is not recognized as an internal or external command,
operable program or batch file."
This error occours when it is not able to find the executable file... but same thing I am able to execute from the command prompt. So I feel this problem is some where related to the path setting of windows. If some one can solve this problem or sugesst the how to set the path for window it will be help full..
waiting for reply

View 2 Replies


ADVERTISEMENT

Best Method For Using FTP Command Xp_cmdshell Or Execute Process Task

Dec 8, 2005

Hi, I need to send a table data into flat and then ftp into different location.
I was using xp_cmdshell via sql task but my network engineer is saying that this xp_cmdshell will break the security and recomond to use "Execute Process Task". If i'm using this task getting the below error.
Could you advice me regrding network engineer thought and any solution for avoiding this error.


---------------------------
Execute Process Task: C:WINDOWSsystem32ftp.exe
---------------------------
CreateProcessTask 'DTSTask_DTSCreateProcessTask_1': Process returned code 2, which does not match the specified SuccessReturnCode of 0.
---------------------------
Thanks,

View 1 Replies View Related

Other Way To Execute The Xp_cmdshell Command On Remote Databases From Local?

Nov 14, 2007

Hi all,


Criteria:

We connect to the remote database servers through the network from loca by using Query Analyzer.
Previously we were able to execute the xp_cmdshell command from local Query Analyzer to fetch the remote databases data.
But now we are unable to execute the xp_cmdshell command on remote databases from local Query Analyzer
We do not know what happened but i think due to network updates this command is not able to execute...


For ex:
Previously i was able to execute master..xp_cmdshell 'net start' from local Query Analyzer.But now not able to execute


Now my question is, is there any other way(Directly or indirectly) to execute the xp_cmdshell command on remote databases from local?


Note : we are able to execute this command on remote Query Analyzer but not from local QA

Any suggestions would be very very helpful to me?


Thanks in advance,



View 6 Replies View Related

Command Works In DOS But Not In Xp_cmdshell

Jul 20, 2005

Can anyone give clues as to why the same copy command works inDOS and not in xp_command shell.I am an admin in both servers andin the database.The results indicate one file is copied but no file is foundat destination.Your input is appreciatedVincentocopy "D:Program FilesMicrosoft SQLServerMSSQLBACKUPQMISDEVack1.txt" "\corp156d$Program FilesMicrosoft SQLServerMSSQLBACKUPQMISDEV"works just fine butusemasterexec xp_cmdshell 'copy "D:Program FilesMicrosoft SQLServerMSSQLBACKUPQMISDEVack1.txt" "\corp156d$Program FilesMicrosoft SQLServerMSSQLBACKUPQMISDEV"'

View 3 Replies View Related

Use Xp_cmdshell To Call Winzip With The Command

Feb 23, 2004

Hello,
how may use xp_cmdshell to call winzip with the command,
i wrote this but it doesn't work ;

declare @cmd varchar(2000)
select @cmd = 'c:program_fileswinzipWzunzip.exe c:AttatchmentsTEST_PJ.zip c:AttatchmentsTEST_PJ.zip'
exec master..xp_cmdshell @cmd

View 3 Replies View Related

How To Grant Execute On Xp_cmdshell??

Apr 2, 2002

Can anyone help me please.
Healp please.
Does anybody know how to make xp cmdshell runnable for users other than Admin. It should be possible to grant execute to others, but i can't figure out how.

This is what i found:

Be aware that when you grant execute permission for xp_cmdshell to users, the users will be able to execute any operating-system command at the Windows NT command shell that the account running SQL Server (typically local system) has privilege to execute.

To restrict xp_cmdshell access to users who have administrator permission on the Windows NT-based computer where SQL Server is running, use SQL Setup or SQL Enterprise Manager to set the server options, selecting the "xp_cmdshell - Impersonates Client" option. With this option selected, only users who have connected to SQL Server via a trusted connection and are members of the local Administrators group on that computer are allowed to use xp_cmdshell. The commands run by xp_cmdshell continue to execute in the server's security context.

View 1 Replies View Related

Execute Xp_cmdshell And Other SA Storedproc

Mar 8, 2004

Hi all,

I have to execute stored procedures containing
xp_cmdshell and certain system storedprocedures in msdb and master
with a user who is not SA.
(i.e iam able to execute stored procedures when i log as sa,
but any other user cannot run them)

Pls tell how to do this, it is quite urgent.

View 1 Replies View Related

Xp_cmdshell Command Causing Database To Lock-up

Nov 26, 2002

I am in the process of writing a stored procedure that takes data from a table, within a cursor, and puts that data to the network server via the xp_cmdshell procedure. The xp_cmdshell command is at the end of the cursor in the SP.

I have worked with the admins on getting the proper permissions to execute this procedure and have tested it by running the procedure directly in Query Analyzer and by calling it in Query Analyzer successfully.

However when I try to call this procedure from another programming envirnoment, once the xp_cmdshell process is called, the procedure locks up and blocks the rest of the process, including the other software programming environment. When I look at the error log, it indicates that correct command, as a matter of fact I have copied the log file command into Query Analyzer and ran the procedure successfully. So for some reason, the statement is not being committed or there is some kind of threading issue I do not know how to address.

If anyone out there has any suggestions or has a simular problem in the past and knows how to address it, it would be greatly appreciated.

Thanks!

View 4 Replies View Related

RDA Push Command Failing ...

May 30, 2006

Hi,

I am using the Pull command to pull two fields, on is the primary ID (int) non identity and the other is Description which comes down as an ntext type. This works fine but if I change the description and use the push command I get the following error:-

The Query processor could not produce a query from the optimizer because a query cannot update a text, ntext, or image column and a clustering key at the same time.



I am really stuck with this one so if anyone can shed some light on it I would be much appreciated.



Cheers,



Jiggy!

View 3 Replies View Related

Permissions For Non Sa User To Execute Xp_cmdShell

Mar 6, 2008

Hi,    I want to execute BCP in Query Analyser in SQL Server 2005 Express for that i surf on net and find that i should execute BCP under xp_cmdShell, That works good for addministritative account on SQL. But i want the working will be done by a non administrative account or non 'sa' user.How can i assign a non sa User permissions to execute xp_cmdShell? or just tell me any other alternative way to run BCP in Query Analyser or code behined. thanx 

View 1 Replies View Related

Xp_cmdshell Execute Rights (2005)

Sep 11, 2006

I was trying to grant access for an application user for executing xp_cmdshell, but I got some error message saying that either doesn't the user exist, or I don't have the permissions to grant this. Does the user need to be a user in Master ? Or, don't I when logged in as "sa" have the sufficient permissions to grant execute on a SP in master?

I solved it by checking "Control server" under "Properties" > "Securables"
for the login, but I don't actually want this login to have full control.

(And yes, I've read that allowing xp_cmdshell usage isn't recommended at all.)

View 3 Replies View Related

Execute SSIS Package From SP Without Xp_cmdshell?

Nov 12, 2006

A developer needs to execute an SSIS package from a stored procedure and I do not want to enable xp_cmdshell on SQL 2005.

One suggestion is to have the application invoke dtexec on the client PC, but this would cause the package to be executed on the client and also requires some SSIS components be installed on each client.

Another idea is to configure a Windows Service to execute dtexec, but I do not know the risks of this approach. Any thoughts?

Thanks, Dave

View 1 Replies View Related

Execute SSIS Package From Xp_cmdshell?

Mar 19, 2008

How to execute SSIS package from CMD or using xp_cmdshell?
SSIS package is saved in the folder of the integration services Db.

Thanks in advance.

View 2 Replies View Related

Xp_cmdshell And Pass Command Line Parameters To .exe File

Jul 20, 2005

I need to execute xp_cmdshell in a trigger and pass a command lineparameter to the .exe programi.e. I have a .exe program c:program filessavedata.exeIn the trigger I have a parameter @Id bigintI need to pass the parameter @Id to savedata.exeIn the trigger, I am tryingEXEC master..xp_cmdshell 'cmd.exe /C "c:program filessavedata.exe "'+ CAST(@Id as varchar)BUT this does not work.Can someone please help me with how to do this?Thanks,db

View 1 Replies View Related

Calling Eventcreate Command From Xp_cmdshell Store Procedure

Feb 15, 2008



Hi,

I want log event in event logger using xp_cmdshell store procedure.
I am calling eventcreate dos command.


xp_cmdshell 'C:> eventcreate /S \servername /L Application /T Success /SO Application Name /ID 1754 /D €œDescription of event€? '

I am getting error....


Incorrect syntax near 'eventcreate' /S \206.245.13.94' /L Application' /T Error' /SO WIPError'/ID 123'/D "Testing"'.


please help me.

thanks,

Chetan S. Raut.

View 5 Replies View Related

Xp_cmdshell - Need To Execute External Program Asynchonous

Oct 21, 2004

hi,

i need to start an external program (vb.net) from within a trigger. via xp_cmdshell everything works fine except that the execution of the trigger waits for the vb-program to finish.

now i tried a workaround with a "starter application" which only calls the vb.net program (asynchronous) an ends.

this works fine from a dos prompt (command prompt returns immediately and vb.net task is running). but when i call the starter app from the trigger with xp_cmdshell, the behavior is the same as before: execution does not continue until the vb.net task ends.

any other ideas that could solve my problem? submitting an agent-job is not fine for me because i need to supply parameters to the called program and maybe i need call it more than once at the same time.

thanks
thomas

View 2 Replies View Related

Can't Execute Master.dbo.xp_cmdshell Throught A Variable.

Dec 5, 2007



Hi all.

I've previous posted a message with error building the expression of the dtexec.exe string. But now, the problem is other, and I've decided to create other threat.

Here is what I'm doing:
I've a SP that receives every parameter so I can build my dtexec.exe statement to be executed by a variable with something like this exec @rc = master.dbo.xp_cmdshell @CMD


Till now I have no problem executing it, not from a variable, but just with the statement itself, like this:
exec master.dbo.xp_cmdshell 'C:PROGRA~2MICROS~290DTSBINNDTEXEC.EXE /SQ PACKAGE /SET "Package.Variables[PERIOD].Value";20070101'.

But now, I have this SP that builds the string into a variable and then I just want to execute it throught the variable like this: exec @rc = master.dbo.xp_cmdshell @CMD.

When I make a SELECT @CMD just before the exec @rc = master.dbo.xp_cmdshell @CMD, so it prints the builded string, copy it and pasted to exec master.dbo.xp_cmdshell 'copied string' it works fine. But the step of exec @rc = master.dbo.xp_cmdshell @CMD returns the error:
The filename, directory name, or volume label syntax is incorrect.

Why is this, if I copy the generated string and execute it by the other way it works fine, but executing the generated string throught the variable it gives me that error?

View 4 Replies View Related

Operationg System Command (CmdExec) Job Failing

Nov 15, 2006

I have sql 2000 job that has been setup as a "Operating System Command (CmdExec) job. I am logged into the SQL Server as DomainNameSQLAdmin this domain account is part of the Administrator group on the SQL Server that the job in running on. This account has SysAdmin rights and is also starting the MSSQLSERVER Service and SQLSERVERAGENT Service on the same machine.

The job just copies files from one directory to another, here's the code.

D:
cd MSSQLBACKUPAPAP_Primary
xcopy *.* D:MSSQLBACKUPAP /s/y/d

When run as a job, with the owner of the job being DomainNameSQLAdmin the job fails with the following error message: Executed as user: DomainNameSQLAdmin. The process could not be created for step 1 of job 0x822E9AD29DCAAF4196369A46C7FE212A (reason: Access is denied). The step failed.

Here's the weird part if I open a command window on the sql server and run the batch it works fine.

I even tried executing the commands via xp_cmdshell but that didn't work either, I recieved the message: (1 row(s) affected) with the output being NULL and the file was never copied.

Anyone have an idea whats going on?

View 4 Replies View Related

Job To Execute DTS Package Failing....

May 15, 2001

I have recently created several DTS Packages and scheduled them to run nightly. The Packages complete succesfully when executed from the DTS Designer. However, when they are executed by a scheduled job, the following error results....
DTSRun: Loading... DTSRun: Executing... Error: -2147220499 (800403ED); Provider Error: 0 (0) Error string: No Steps have been defined for the transformation Package. Error source: Microsoft Data Transformation Services (DTS) Package Help file: sqldts.hlp Help context: 700. Process Exit Code 1. The step failed.

This packages exist and are running via scheduled jobs on another server. Does anyone know what is causing this error????
thanks!

View 3 Replies View Related

Failing Execute SQL Task

May 9, 2007

Inside of an SQL Task (below), I have a call to a stored procedure with 7 parms.



[Audit].[spBatchPackage_OnExtract] ?, ?, ?, ?, ?, ?, ?



User:: ParentExecution_Idx Long

User:: Batch_Idx Long

System:: PackageName Nvarchar

System:: PackageID GUID

User:: TargetTable Nvarchar

System:: ContainerStartTime DBTimestamp

User:: DataFilePattern Nvarchar



In my SP I have this:

ALTER PROCEDURE [Audit].[spBatchPackage_OnExtract]

@Execution_Idx int

,@Batch_Idx int

,@Source nvarchar(1024)

,@SourceId uniqueidentifier

,@Destination nvarchar(1024)

,@StartTime DATETIME

,@FileSpecification nvarchar(2)



When I execute the SQL Task, I get this error:



[Execute SQL Task] Error: Executing the query "[Audit].[spBatchPackage_OnExtract] ?, ?, ?, ?, ?, ?, ?" failed with the following error: "Invalid character value for cast specification". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.



Any help on clearing up this error would be appreciated!

View 12 Replies View Related

Impersonation Through EXECUTE AS Failing

May 21, 2008

Hello all-
Before I go any further, I have followed http://msdn.microsoft.com/en-us/library/ms188304.aspx as best possible. I am attempting to send mail through a DML trigger. We'll call the database 'DB', and it is owned by a domain account named 'DOMAINAcct'. The trigger simply blocks any CUD operations on a table which we'll call 'Tbl', and sends an email. Hence, it looks something like...

CREATE TRIGGER [dbo].[TR_Tbl_BlockChanges]
ON [dbo].[Tbl]
WITH EXECUTE AS OWNER
INSTEAD OF INSERT,DELETE,UPDATE
AS
EXEC [msdb].[dbo].[sp_send_dbmail] @profile_name = 'AcctMail', @recipients = 'foo@bar.com', @subject = N'CUD operations not allowed on Tbl', @body = N'Blocked'

AcctMail is a valid profile and operates correctly. I have created the DOMAINAcct user in msdb, given it the AUTHENTICATE permission, and added it to the DatabaseMailUserRole. When the trigger fires, according to the article, the security context should switch to dbo (DOMAINAcct), then be successful when attempting to execute the msdb sproc. Instead I get the usual:
Msg 229, Level 14, State 5, Procedure sp_send_dbmail, Line 1
The EXECUTE permission was denied on the object 'sp_send_dbmail', database 'msdb', schema 'dbo'.

Thoughts?

View 4 Replies View Related

Execute Xp_cmdshell From Store Procedure (called From Aspx)

May 21, 2004

Hi, I have been searching for an answer to allow me to execute xp_cmdshell from withing store prcedure by calling the store procedure from an aspx via click on a button. This is what I found from my reserch but was not able to know where to set the rights and what each of them means:
"To run xp_cmdshell for a non-system administrator user, you must grant the following rights.
MSSQLServer and SQLServerAgent Services
Act as part of the Operating System.
Increase Quotas.
Replace a process level token.
Log on as a batch job."

The above quote was from the following link:
http://support.microsoft.com/default.aspx?scid=kb;en-us;264155

The bottom line is to be able to call a store procedure from an aspx page to execute the code which contain xp_cmdshell command, an example of such command is like:
------------------------------------------------------------
EXEC master..xp_cmdshell 'dir d:BT_importDatasales_option_price_report.csv'

Thanks for your help
ehx5

View 1 Replies View Related

Cannot Execute Xp_cmdshell. Access Is Denied While Copying Data Over The Network

Aug 7, 2006

Hi,I am having
some trouble copying data over my workgroup network from my Windows
2003 Server Machine (machineA with SQL SERVER 2005) to one of my
network Machine's drive(MachineB).Here is the T-SQL code that I am trying to execute:EXEC xp_cmdshell 'copy D:Datafile.txt  \MachineBDocuments'Whenever
I tried to execute the above piece of code, I get the error message
"Access is denied", but if I try to copy the file from the Command
Prompt (cmd.exe) with the copy command, the file copies fine over the
network.I have already searched over the internet and I found
out that loads of people have the same issue, and they were suggested
something like this:"Check in Services and make sure that the MSSQLServer service is run as
a domain user and that domain user has rights to these network
resources."Well
it sounds plausible, but I don't know what are the exact steps to do
this. How do I know which user is running the MSSQL Server service? Are
they referring to the user which I use to connect to my SQL Server
Database engine throuhg the SQL Server Management Studio?Also they are suggesting 'domain user', and as I said before I do not have domain network just regular simple workgroup network.Here
are some details of the user that I use to login. I generally login
into my Windows 2003 Server machine with user called 'User1' and I use
the same 'User1' to connect to SQL Server through the Management Studio
Screen.Should I create a user called 'User1' on my MachineB(Destination Machine)?I would really appreciate, if someone can give me detailed steps explaning how to solve this problem.Thank you very much once again.

View 11 Replies View Related

Cannot Execute Xp_cmdshell. Access Is Denied While Copying Data Over The Network

Aug 7, 2006

Hi,

I am having some trouble copying data over my workgroup network from my Windows 2003 Server Machine (machineA with SQL SERVER 2005) to one of my network Machine's drive(MachineB).
Here is the T-SQL code that I am trying to execute:

EXEC xp_cmdshell 'copy D:Datafile.txt \MachineBDocuments'

Whenever I tried to execute the above piece of code, I get the error message "Access is denied", but if I try to copy the file from the Command Prompt (cmd.exe) with the copy command, the file copies fine over the network.

I have already searched over the internet and I found out that loads of people have the same issue, and they were suggested something like this:
"Check in Services and make sure that the MSSQLServer service is run as
a domain user and that domain user has rights to these network
resources."

Well it sounds plausible, but I don't know what are the exact steps to do this. How do I know which user is running the MSSQL Server service? Are they referring to the user which I use to connect to my SQL Server Database engine throuhg the SQL Server Management Studio?
Also they are suggesting 'domain user', and as I said before I do not have domain network just regular simple workgroup network.

Here are some details of the user that I use to login. I generally login into my Windows 2003 Server machine with user called 'User1' and I use the same 'User1' to connect to SQL Server through the Management Studio Screen.
Should I create a user called 'User1' on my MachineB(Destination Machine)?

I would really appreciate, if someone can give me detailed steps explaning how to solve this problem.

Thank you very much once again.

View 18 Replies View Related

Parameters Failing When Supplied By A Query And Set Up To Execute

Mar 10, 2006

I have a query that provides a list of detachments that are used as a parameter for the user to select when running a report.

It works fine.

I want to set up this report to also run on a schedule.

When I set the prameters on the report for any value other than the first one in the list it fails to execute with the following error.

Parameter validation failed. It is not possible to provide valid values for all parameters. (rsParameterError) (there are no other details provided)

The query results are

All
A
B
C
D
E
G
H
I
N
V
W
X



I get this error if I input a value in the list other than All or any value that is not in the list. Any suggestions?



We are running Report Services 2000 SP1



Many thanks Ayla

View 6 Replies View Related

Using XP_CmdShell To Execute BCP Utility With QUERYOUT. How To Control The OWNER Of The File Created?

Jan 29, 2008

I need the file created by my BCP QUERYOUT command I'm executing from XP_CmdShell in Transact-SQL to have a specific OWNER. I've tried using the sp_xp_cmdshell_proxy_account to setup the correct owner. The owner is always SERVERNAMEAdministrators.

thanks,

jim




View 1 Replies View Related

DTS Execute SQL Task Terminates Without Failing When Error Occurs (SP3)

Mar 21, 2001

I'm running SQL Server 7.0 SP3 and having trouble with DTS.

I have an Execute SQL Task that runs several stored procedures. When one of the stored procedures fails, the Execute SQL Task just terminates without failing.

I found a knowledge base article (Q238523) dealing with this situation but it was supposedly fixed in SP2 - I have SP3! The other work around suggested, issuing a SET NOCOUNT ON, does not always work.

Has anyone else run into this or have any other suggestions.

I hate the thought of spending days doing another work around in order get basic DTS functionalty to work as it should!

Thanks!

Jerry Dunn
gdunnjr@yahoo.com

View 2 Replies View Related

SSIS - For Each Loop With Insert In Execute Task Failing

Oct 19, 2015

I have ForEach Loop using Foreach File Enumerator. Within this loop I have SQL Task containing an Insert statement. When I run the Insert statement in query builder the transaction inserts data into a table as expected.

However, when actually running the process I am getting the error message:

Executing the query "INSERT INTO dbo.TEST_TABLE
..." failed with the following error: "Value does not fall within the expected range.". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.

I currently have the ResultSet to "None" and have defined the parameter I am using. Where the process seems to joke is on my file_Name variable will I am trying to insert only part of the file name.

My insert statement looks as follows:

INSERT INTO dbo.TEST_TABLE
(IID, AN8, File_Type, IB_OB, File_Name, Processed_Flag, ReceiptDateTime)
VALUES
(
'1111',
'123',
'888',
'IB',
RIGHT(LEFT(?, LEN(?) - 4), LEN(?) - 24),
'I',
GETDATE())

View 0 Replies View Related

Execute SQL Tasks Failing For Duplicate Syntax Between DEV And Production DB

Mar 28, 2007

Newbie here...be patient with me!

I added tasks to refresh two tables (delete from, insert into, update) to an SSIS project . I have them running from the WinXP scheduler. The issue:

In dev the tasks integrate and execute successfully from scheduler

In prod I can right click and execute each of the three tasks without any problem, but the same tasks cause my project to fail when executed from scheduler


Questions:
Any ideas about what I am failing to see?
How do I get a meaningful log messages from the tasks that are failing?

Thanks for your ideas...

Installed Edition: IDE Standard

SQL Server Analysis Services
Microsoft SQL Server Analysis Services Designer
Version 9.00.1399.00

SQL Server Integration Services
Microsoft SQL Server Integration Services Designer
Version 9.00.1399.00

SQL Server Reporting Services
Microsoft SQL Server Reporting Services Designers
Version 9.00.1399.00

Microsoft Visual Studio 2005
Version 8.0.50727.42 (RTM.050727-4200)
Microsoft .NET Framework
Version 2.0.50727

Installed Edition: IDE Standard

SQL Server Analysis Services
Microsoft SQL Server Analysis Services Designer
Version 9.00.1399.00

SQL Server Integration Services
Microsoft SQL Server Integration Services Designer
Version 9.00.1399.00

SQL Server Reporting Services
Microsoft SQL Server Reporting Services Designers
Version 9.00.1399.00

View 4 Replies View Related

Integration Services :: Execute Process Task Failing

Dec 1, 2015

I have an SSIS package which calls a command line app.When run in BIDS, it executes normally. The command line app is passed the arguments, does what it needs to do.When called as a SQL Agent Job (by the agent, or by me) it fails when calling the app, giving an exit code of 2 (which is an exception trapped by a try-catch). The SQL Agent service is running under my user (it's a test environment). The argument passed (from the log) is valid, and I've run it against the app, it provides the appropriate output.I can't for the life of me figure out what's going wrong.The app is passed an argument of a path and a password, and applies the password to the file, using interop.

View 13 Replies View Related

Execute SET Command In VB .NET

Feb 27, 2008

I have to execute this command on my vs.net code:





Code Snippet

SET IDENTITY_INSERT table name ON
I use this to run it:





Code Snippet

.

.

.


Dim command As SqlCommand = New SqlCommand("SET IDENTITY_INSERT table name ON", msSqlConexion)
command.ExecuteNonQuery()
It doesn't throw any kind of errors, but it actually don't execute it, and If I run it on console it works ok.

any help?

View 6 Replies View Related

Command Or Execute Not Working

Mar 11, 2007

Can anybody help me with this command code that stops at the execute and eventually gives timeout.


Dim MM_Cmd, strSQL, strSQL2, strSQL3, strSQL4

Set MM_Cmd = Server.CreateObject("ADODB.Command")
MM_Cmd.ActiveConnection = MM_connAdmin_STRING
strSQL = "update Products_Categories set Depth=NULL, Lineage=''"
MM_Cmd.CommandText = strSQL
MM_Cmd.CommandType = 1
'MM_Cmd.CommandTimeout = 0
MM_Cmd.Prepared = True
MM_Cmd.Execute strSQL
Set MM_Cmd = Nothing

Regards
Amazing

View 2 Replies View Related

Execute Create Table Command From Asp.net

Jul 25, 2006

I have a little application that I have designed where I need to be able to execute create table and create function comands against the database.
It seems that it does not like my sql file. Does anyone know of a different method of doing this?
 
Error message
Line 2: Incorrect syntax near 'GO'.
Line 4: Incorrect syntax near 'GO'.
Line 8: Incorrect syntax near 'GO'.
'CREATE FUNCTION' must be the first statement in a query batch.
Must declare the variable '@usb'.
Must declare the variable '@usb'.
Must declare the variable '@i'.
A RETURN statement with a return value cannot be used in this context.
Line 89: Incorrect syntax near 'GO'.
Line 91: Incorrect syntax near 'GO'.
Line 94: Incorrect syntax near 'GO'.
 
Protected Sub Install()
   Dim err As String = ""
While err.Length < 1
'      Dim your StreamReader
      Dim TextFileStream As System.IO.TextReader
      'Load the textfile into the stream
      TextFileStream = System.IO.File.OpenText(Request.PhysicalApplicationPath & "Scripts.sql")
      'Read to the end of the file into a String variable.
      executesql(TextFileStream.ReadToEnd, err)
 
      err = "Susscessful"
End While
If err = "Susscessful" Then
      Response.Redirect("Default.aspx")
Else
      Me.lblError.Text = err
End If
End Sub
Private Function executesql(ByVal s As String, ByRef err As String) As Boolean
Try
      Dim conn As New Data.SqlClient.SqlConnection(GenConString())
      Dim cmd As New Data.SqlClient.SqlCommand(s, conn)
      conn.Open()
      cmd.ExecuteNonQuery()
      conn.Close()
      Return True
   Catch ex As Exception
      err = ex.Message.ToString
      Return False
   End Try
End Function


Example sql file
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[MyFunc]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[MyFunc]
GO
CREATE FUNCTION [dbo].[MyFunc]
(
-- Add the parameters for the function here

)
RETURNS varchar(1000)
AS
BEGIN
-- Declare the return variable here
DECLARE @Result varchar(1000)
-- Add the T-SQL statements to compute the return value here
-- Do something here
-- Return the result of the function
RETURN @Result
END
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

View 1 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved