EXEC xp_cmdshell

Hi Guys,
In SS 2008 r2 im trying to unpack a zip file trough the cmd.
exec xp_cmdshell 'set PATH=%PATH%;C:\Program Files (x86)\7-Zip\
echo %PATH%
7z'
go
exec xp_cmdshell '7z e D:\Share\restorefile.bak.zip -od:\Share'
go
is there any way to get this working from SS? CMD keeps on telling that 7z is not recognized or the function e is not recognized. Code is going to be placed in a job that runs daily.

First of all, have you verified that 7z.exe is strictly a command-line utility and does not have any desktop interaction? Because if it can pop up messages boxes, windows or whatever, this is a dead end and the rest of the discussion is moot.
No, you should not add anything to PATH through the control panel. To that end you would need to change the path for the service account for SQL Server. And two years later when you move the database to a new server, you would have forgotten all about it,
and wonder why things has stopped working.
Eric's post has some errors. When you get that message in a command-line window it is typically because you have the double quotes wrong. Here is a corrected version of Eric's command:
exec xp_cmdshell  '"C:\Program Files(x86)\7-Zip\7z.exe" x "D:\Share\restorefile.bak.zip" -o"d:\Share"'
But as I don't have 7x installed, I cannot vouch for that it is entirely correct.
And I stress again that you should consider alternatives. It is not the job of SQL Server to unzip files.
Erland Sommarskog, SQL Server MVP, [email protected]

Similar Messages

  • Exec XP_CMDSHELL cannot find store procedure problem

    I run EXEC sp_configure 'xp_cmdshell', 1
    Message is"....change from 1 to 1 "
    Then
    EXECXP_CMDSHELL 'Dir N:'
    cannot find store procedure xp_cmdshell
    I check master database.
    No dbo.xp_cmdshell under store procedure.
    How to fix it? I need run command
    EXECXP_CMDSHELL 'Dir N:'
    Thanks

    Hallo Bestrongself,
    - what SQL Server version do you use?
    - since SQL 2005 xp_cmdshell is located in the sys-schema and the procedure itself is located in the resource database of Microsoft SQL Server.
    You can check xp_cmdshell by using the following command:
    SELECT * FROM sys.all_objects WHERE name = 'XP_CMDSHELL'
    I bet you will see it in the master database because you cannot drop system procedures and will return an error if you try to do so:
    USE master;
    GO
    BEGIN TRANSACTION
    DROP PROCEDURE dbo.xp_cmdshell;
    DROP PROCEDURE sys.xp_cmdshell;
    DROP PROCEDURE xp_cmdshell;
    ROLLBACK TRANSACTION
    To execute xp_cmdshell you need to have [CONTROL SERVER] permissions otherwise it won't work. Let's say I have a login which I grant exclusive permissions to execute xp_cmdshell it will fail!
    USE master;
    GO
    -- create the login and the user in master-database
    CREATE LOGIN test WITH PASSWORD = 'glmdpf12345', CHECK_POLICY = OFF, CHECK_EXPIRATION = OFF;
    CREATE USER test FROM LOGIN [Test];
    GO
    -- grant explicit permission to execute the xp_cmdshell
    GRANT EXECUTE ON sys.xp_cmdshell TO test;
    GO
    -- tryp to execute xp_cmdshell as test
    EXECUTE AS login = 'test'
    EXEC xp_cmdshell 'DIR C:';
    REVERT
    -- Housekeeping
    REVOKE EXECUTE ON sys.xp_cmdshell TO test;
    DROP USER 'test';
    DROP LOGIN 'test';
    As you can see from the above statement the login "Test" got exclusive permission to execute xp_cmdshell but the execution will fail with the following error message:
    The xp_cmdshell proxy account information cannot be retrieved or is invalid. Verify that the '##xp_cmdshell_proxy_account##' credential exists and contains valid information.
    The above error message is clear. Test is a "normal" user which has the permission to execute the proc BUT due to missing permissions to retrieve the information about the service account it fails!
    You have to grant SERVER CONTROL to the account.
    So - next step...
    What is your permission on server level?
    You can check your permissions by using the following statement:
    -- what are my permissions on server level
    -- check for CONTROL SERVER!
    SELECT * FROM sys.fn_my_permissions (NULL, 'SERVER') ORDER BY permission_name;
    -- what are my permissions for the object xp_cmdshell
    SELECT * FROM sys.fn_my_permissions('xp_cmdshell', 'OBJECT');
    Can you provide us with the results of the above query?
    BTW: xp_cmdshell is a well documented statement and official command which is fully supported by Microsoft. You can find all information about functionality and security of xp_cmdshell here:
    http://technet.microsoft.com/en-us/library/ms175046.aspx
    MCM - SQL Server 2008
    MCSE - SQL Server 2012
    db Berater GmbH
    SQL Server Blog (german only)

  • BCP is not working in when i am executing using xp_cmdshell

    Declare @cmd varchar(300)
    Set @cmd=
    'bcp "SELECT definition + char(13) + ''GO'' FROM test.sys.sql_modules s INNER JOIN test.sys.procedures p ON [s].[object_id] = [p].[object_id] 
     WHERE p.name LIKE ''create%''" queryout "V:\SQLBackups\SP_scripts.sql" -C -T -t -w'
     exec xp_cmdshell @cmd
    below is the result i am getting its not creating any sql script its working perfectly from cmd prompt
    usage: bcp {dbtable | query} {in | out | queryout | format} datafile
      [-m maxerrors]            [-f formatfile]          [-e errfile]
      [-F firstrow]             [-L lastrow]             [-b batchsize]
      [-n native type]          [-c character type]      [-w wide character type]
      [-N keep non-text native] [-V file format version] [-q quoted identifier]
      [-C code page specifier]  [-t field terminator]    [-r row terminator]
      [-i inputfile]            [-o outfile]             [-a packetsize]
      [-S server name]          [-U username]            [-P password]
      [-T trusted connection]   [-v version]             [-R regional enable]
      [-k keep null values]     [-E keep identity values]
      [-h "load hints"]         [-x generate xml format file]
      [-d database name]        [-K application intent]
    NULL
    any help is highly appreciated 
    Thanks
    AK

    issue got resolved sql command should be in single line :)

  • Problems enabling xp_cmdshell

    We migrated a SQL Server 2005 server to SQL 2008R2 SP3 this past Sunday, with one named instance. One of the things we missed was that xp_cmdshell was enabled on the old server. The SQL server name is fl2000-sql002 and the SProc is using this code:
    SET @bcpCommand
    = 'bcp.exe AdjustmentRequests.##AdjustmentRequestCSVFinal out "\\fl2000-netcon01\DefPath\Charge Imports\result.csv" -S fl2000-sql002 -U AdjustmentRequests -P [Pwd] -t, -c'
    EXEC
    master..xp_cmdshell
    @bcpCommand
    The programmers request was to grant the local SQL ID named 'AdjustmentRequests' the ability to execute xp_cmdshell, but I want to use a generic SQLProxy account in case future SProc's also need the
    ability. Because it is referencing a remote UNC path, I created a new dedicated domain proxy account named SQL002DB.Proxy.
    I've done this before years ago but I didn't document the exact steps, so I was searching for the process again. I tried a few different links, and then ended up on the link I recognized from the last setup on one of our other SQL servers...
    http://sqlblog.com/blogs/tibor_karaszi/archive/2007/08/23/xp-cmdshell-and-permissions.aspx.
    At this point in time, the instance doesn't not have a login for the SQLProxy account, nor the domain\SQL002db.Proxy account, there are not any entries in the Credentials, and there are not any entries in the SQL Agent\Proxies\OperatingSystem(CmdExec)
    containers. I refreshed all containers to confirm.
    The commands I'm attempting to use are below.
    --1, allow   xp_cmdshell
    EXEC sp_configure 'xp_cmdshell', 1
    RECONFIGURE
    GO
    --2, grant permission to xp_cmdshell
    USE master
    CREATE LOGIN SQLProxy WITH PASSWORD =   'XP_Cmdshell'
    CREATE USER SQLProxy FROM LOGIN SQLProxy
    GRANT EXECUTE ON xp_cmdshell TO SQLProxy
    EXECUTE AS login = 'SQLProxy'
    EXEC sp_xp_cmdshell_proxy_account   'Domain\SQL002DB.Proxy','Pwd'
    EXECUTE AS login = 'SQLProxy'
    EXEC xp_cmdshell 'DIR C:\*.*'
    REVERT
    Regardless if I login as sa or login with my domain account which is a member of the sysadmin role, I receive these messages upon execution:
    Configuration option 'xp_cmdshell' changed from 1 to 1. Run the RECONFIGURE statement to install.
    Msg 15023, Level 16, State 1, Line 4
    User, group, or role 'SQLProxy' already exists in the current database.
    Msg 229, Level 14, State 5, Procedure sp_xp_cmdshell_proxy_account, Line 1
    The EXECUTE permission was denied on the object 'sp_xp_cmdshell_proxy_account', database 'mssqlsystemresource', schema 'sys'.
    Msg 229, Level 14, State 5, Procedure xp_cmdshell, Line 1
    The EXECUTE permission was denied on the object 'xp_cmdshell', database 'mssqlsystemresource', schema 'sys'.
    Now I see the SQLProxy login ID listed, but nothing else. What am I doing wrong? The staff are sharpening their pitchforks because they are having to run this process manually.

    Logged in as sa:
    EXEC
    sp_xp_cmdshell_proxy_account[Domain\SQL002DB.Proxy],
    'Pwd'
    Msg 15137, Level 16, State 1, Procedure sp_xp_cmdshell_proxy_account, Line 1
    An error occurred during the execution of sp_xp_cmdshell_proxy_account. Possible reasons: the provided account was invalid or the '##xp_cmdshell_proxy_account##' credential could not be created. Error code: '5'.
    USE
    master;
    GO
    CREATE
    USER [Domain\SQL002DB.Proxy]
    FOR
    LOGIN [Domain\SQL002DB.Proxy];
    GRANT
    EXECUTE
    ON
    xp_cmdshell
    TO [Domain\SQL002DB.Proxy];
    Msg 15023, Level 16, State 1, Line 1
    User, group, or role 'Domain\SQL002DB.Proxy' already exists in the current database.

  • Xp_cmdshell proxy account

    hello,
    i have a weird case that i have two accounts on a database server, lets say AD and AL. the AD is a domain account and the AL is a local account. both of them are local administrators on that database server and both of them is a sysadmin on the sql
    server. i've enabled the xp_cmdshell, and i've created the ##xp_cmdshell_proxy_account##. now, in the ##xp_cmdshell_proxy_account## credential properties if i use the AD in the Identity field, the stored procedure that uses the xp_cmdshell works
    fine, but if i use the AL account i got the following error:
    "An error occurred during the execution of xp_cmdshell. A call to 'LogonUserW' failed with error code: '1385'."
    i've searched the error and i found something in http://msdn.microsoft.com/en-us/library/ms681385.aspx that the error code 1385 means (but i'm not sure
    if those codes are related to the error i'm getting):
    "Logon failure: the user has not been granted the requested logon type at this computer."
    i've tried to login with the AL account to the sql server and run for example "exec xp_cmdshell 'echo 123'" and it worked fine!.
    can anybody explain this or at least shed some light on the places that i didn't configure for the AL user ? 

    Please Check if the AL user has these rights
    Log on as a service (SeServiceLogonRight)
    Act as part of the operating system (SeTcbPrivilege) (only on Windows 2000)
    Log on as a batch job (SeBatchLogonRight) 
    Replace a process-level token (SeAssignPrimaryTokenPrivilege)
    Bypass traverse checking (SeChangeNotifyPrivilege)
    Adjust memory quotas for a process (SeIncreaseQuotaPrivilege)
    Specially
    Log on as a service (SeServiceLogonRight)
    Surender Singh Bhadauria

  • Xp_cmdshell raising error when running script on a remote server by server authentication

    Sqlcmd: Error: Error occurred while opening or operating on file C:\ewApps\Source\MyIssueApp\Scripts\DBScripts\issueUpdateSchemaVersion.sql (Reason: The system cannot find the path specified).
    here is my sql script-
    Declare @ScriptVersion ='1.1'
    Declare @TargetScriptVersionNo = '1.1'
    Declare @DBServerName VARCHAR(50)= 'remote-a'
    Declare @DBName VARCHAR(50)='mydb'
    Declare @FilePath NVARCHAR(MAX)= 'C:\ewApps\Source\MyIssueApp\Scripts\DBScripts\issueUpdateSchemaVersion.sql'
    DECLARE @UserName VARCHAR(10) = 'sa'
    DECLARE @Password VARCHAR(20) = 'sql1k9@abcd'
    DECLARE @Command =''
    set @Command = ' sqlcmd -S ' + @DBServerName + ' -U ' + @UserName + ' -P '+ @Password + ' -d ' + @DBName + ' -i "'+ @FilePathForAllScript + '" -v SubScriptVersion=''' + @VersionNumber + ''''
    EXEC xp_cmdshell @Command
    the generated string @command is -
    sqlcmd -S ewp-dev14 -U sa -P sql2k8@dev14 -d a -i "C:\ewApps\Source\MyIssueApp\Scripts\DBScripts\issueUpdateSchemaVersion.sql" -v SubScriptVersion='1.1'
    and also
    sqlcmd -S ewp-dev14 -U sa -P sql2k8@dev14 -d a -i C:\ewApps\Source\MyIssueApp\Scripts\DBScripts\issueUpdateSchemaVersion.sql -v SubScriptVersion='1.1'
    i think this is a long path related issue, but when i pass a small path, it works like c:\ewapps\issueUpdateSchemaVersion.sql, but i cant use small path , the path mentioned above is mandatory..
    i dont have any space in my path still i have tried it by applying both "" (double codes) and without double codes but its not working, and showing following error-
    Sqlcmd: Error: Error occurred while opening or operating on file C:\ewApps\Source\MyIssueApp\Scripts\DBScripts\issueUpdateSchemaVersion.sql (Reason: The system cannot find the path specified).
    all the above parameters are coming from a batch file.
    Note- My this server is at TFS, can it be an issue ?? please help...

    Yes, files are properly located.
    than what can be the solution for this ??
    Double-check and triple-check. Computers rarely lie. If the machine says The system cannot find the path specified that rarely means
    I'm just too lazy be bothered right now, and that's why I don't find it.
    Run "xp_cmdshell 'DIR'" on various parts in the path to troubleshoot:
    xp_cmdshell 'DIR C:\ewApps\Source\MyIssueApp\Scripts\DBScripts\issueUpdateSchemaVersion.sql'
    xp_cmdshell 'DIR C:\ewApps\Source\MyIssueApp\Scripts\DBScripts\'
    etc, with and without quotes.
    Erland Sommarskog, SQL Server MVP, [email protected]

  • EXECUTE xp_cmdshell AS context of a sysadmin requires ##xp_cmdshell_proxy_account## credential to exist?

    Hi,
    I am unable to use a stored procedure to allow a non-sysadmin to execute in the context of a sysadmin and call xp_cmdshell unless the ##xp_cmdshell_proxy_account## actually exists.
    My understanding is that a sysadmin does not require the use of a proxy in order to execute xp_cmdshell.  However without one set up I receive the following error:
    Msg 15153, Level 16, State 1, Procedure xp_cmdshell, Line 1
    The xp_cmdshell proxy account information cannot be retrieved or is invalid. Verify that the '##xp_cmdshell_proxy_account##' credential exists and contains valid information.
    A little confused as to why the ##xp_cmdshell_proxy_account## needs to be set up and if/how/when the credential identity's details are actually used?
    Regards
    Dan

    I am unable to use a stored procedure to allow a non-sysadmin to execute in the context of a sysadmin and call xp_cmdshell unless the ##xp_cmdshell_proxy_account## actually exists.
    When you use EXECUTE AS in the procedure header, you impersonate a database user, but you don't get any permissions on server level, unless the database is marked as trustworthy. But don't make the database trustworthy, as it can can open a security
    hole.
    Instead a better solution is to create a certificate in the master database, and create a login from that certificate. That is not a login that can acutlly login, but only serves as a placeholder for permissions. In this case, you add the login to the sysadmin
    role. Then you export the certificate to the user database and you sign the procedure with the certificate. Below are the steps to take as a script. For more details on the technique, see this article on my web site:
    http://www.sommarskog.se/grantperm.html
    I also discuss the dangers with trustworthy in more detail in this article.
    USE master
    go
    -- Create certificate in master.
    CREATE CERTIFICATE xp_cmdshell_cert
       ENCRYPTION BY PASSWORD = 'All you need is love'
       WITH SUBJECT = 'For xp_cmdshell privileges',
       START_DATE = '20020101', EXPIRY_DATE = '20200101'
    go
    -- Create a login for the certificate.
    CREATE LOGIN xp_cmdshell_cert_login FROM CERTIFICATE xp_cmdshell_cert
    go
    -- Grant rights for the certificate login.
    EXEC sp_addsrvrolemember xp_cmdshell_cert_login, sysadmin
    go
    -- Save the certificate to disk.
    BACKUP CERTIFICATE xp_cmdshell_cert TO FILE = 'C:\temp\cert.cer'
    WITH PRIVATE KEY (FILE = 'C:\temp\cert.pvk' ,
                      ENCRYPTION BY PASSWORD = 'Tomorrow never knows',
                      DECRYPTION BY PASSWORD = 'All you need is love')
    go
    -- Move to test database.
    USE somedatabase
    go
    -- You procedure here.
    CREATE PROCEDURE run_xp_cmdshell AS
    EXEC xp_cmdshell 'DIR'
    go
    -- Give test user right to execute the procedure.
    GRANT EXECUTE ON run_xp_cmdshell TO someuser
    go
    -- Import the certificate we created in master into the test database.
    CREATE CERTIFICATE xp_cmdshell_cert FROM FILE = 'C:\temp\cert.cer'
    WITH PRIVATE KEY (FILE = 'C:\temp\cert.pvk',
                      DECRYPTION BY PASSWORD = 'Tomorrow never knows',
                      ENCRYPTION BY PASSWORD = 'A day in life')
    go
    -- Delete the files.
    EXEC master..xp_cmdshell 'DEL C:\temp\cert.*', 'no_output'
    go
    -- Sign the test procedures.
    ADD SIGNATURE TO run_xp_cmdshell BY CERTIFICATE xp_cmdshell_cert
        WITH PASSWORD = 'A day in life'
    go
    Erland Sommarskog, SQL Server MVP, [email protected]

  • Procedure to save the output of a query into excel file or flat file

    Procedure to save the output of a query into excel file or flat file
    I want to store the output of my query into a file and then export it from sql server management studio to a desired location using stored procedure.
    I have run the query --
    DECLARE @cmd VARCHAR(255)
    SET @cmd = 'bcp "select * from dbo.test1" queryout "D:\testing2.xlsx;" -U "user-PC\user" -P "" -c '
    Exec xp_cmdshell @cmd
    error message--
    SQLState = 28000, NativeError = 18456
    Error = [Microsoft][SQL Server Native Client 10.0][SQL Server]Login failed for user 'user-PC\user'.
    NULL
    Goel.Aman

    Hello,
    -T:
    Specifies that the bcp utility connects to SQL Server with a trusted connection using integrated security. The security credentials of the network user,
    login_id, and password are not required. If
    –T is not specified, you need to specify
    –U and –P to successfully log in.
    -U:
    Specifies the login ID used to connect to SQL Server.
    Note: When the bcp utility is connecting to SQL Server with a trusted connection using integrated security, use the
    -T option (trusted connection) instead of the
    user name and password combination
    I would suggest you take a look at the following article:
    bcp Utility: http://technet.microsoft.com/en-us/library/ms162802.aspx
    A similar thread regarding this issue:
    http://social.msdn.microsoft.com/Forums/sqlserver/en-US/b450937f-0ef5-427a-ae3b-115335c0d83c/bcp-connection-error-sqlstate-28000-nativeerror-18456?forum=sqldataaccess
    Regards,
    Elvis Long
    TechNet Community Support

  • How to call a SP with dynamic columns and output results into a .csv file via SSIS

    hi Folks, I have a challenging question here. I've created a SP called dbo.ResultsWithDynamicColumns and take one parameter of CONVERT(DATE,GETDATE()), the uniqueness of this SP is that the result does not have fixed columns as it's based on sales from previous
    days. For example, Previous day, customers have purchased 20 products but today , 30 products have been purchased.
    Right now, on SSMS, I am able to execute this SP when supplying  a parameter.  What I want to achieve here is to automate this process and send the result as a .csv file and SFTP to a server. 
    SFTP part is kinda easy as I can call WinSCP with proper script to handle it.  How to export the result of a dynamic SP to a .CSV file? 
    I've tried
    EXEC xp_cmdshell ' BCP " EXEC xxxx.[dbo].[ResultsWithDynamicColumns ]  @dateFrom = ''2014-01-21''"   queryout  "c:\path\xxxx.dat" -T -c'
    SSMS gives the following error as Error = [Microsoft][SQL Server Native Client 10.0]BCP host-files must contain at least one column
    any ideas?
    thanks
    Hui
    --Currently using Reporting Service 2000; Visual Studio .NET 2003; Visual Source Safe SSIS 2008 SSAS 2008, SVN --

    Hey Jakub, thanks and I did see the #temp table issue in our 2008R2.  I finally figured it out in a different way... I manage to modify this dynamic SP to output results into
    a physical table. This table will be dropped and recreated everytime when SP gets executed... After that, I used a SSIS pkg to output this table
    to a file destination which is .csv.  
     The downside is that if this table structure ever gets changed, this SSIS pkg will fail or not fully reflecting the whole table. However, this won't happen often
    and I can live with that at this moment. 
    Thanks
    --Currently using Reporting Service 2000; Visual Studio .NET 2003; Visual Source Safe SSIS 2008 SSAS 2008, SVN --

  • Unable to open the physical file "D:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\abc.mdf". Operating system error 2: "2(The system cannot find the file specified.)".

    hi,
    am running the below command for moving sql serevr mdf and ldf files  from one  drive to another : c  drive to d drive:
    but am getting the below error
    SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\abc.mdf". Operating system error 2: "2(The system cannot find the file specified.)".
    use master
    DECLARE @DBName nvarchar(50)
    SET @DBName = 'CMP_143'
    DECLARE @RC int
    EXEC @RC = sp_detach_db @DBName
    DECLARE @NewPath nvarchar(1000)
    --SET @NewPath = 'E:\Data\Microsoft SQL Server\Data\';
    SET @NewPath = 'D:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\';
    DECLARE @OldPath nvarchar(1000)
    SET @OldPath = 'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\';
    DECLARE @DBFileName nvarchar(100)
    SET @DBFileName = @DBName + '.mdf';
    DECLARE @LogFileName nvarchar(100)
    SET @LogFileName = @DBName + '_log.ldf';
    DECLARE @SRCData nvarchar(1000)
    SET @SRCData = @OldPath + @DBFileName;
    DECLARE @SRCLog nvarchar(1000)
    SET @SRCLog = @OldPath + @LogFileName;
    DECLARE @DESTData nvarchar(1000)
    SET @DESTData = @NewPath + @DBFileName;
    DECLARE @DESTLog nvarchar(1000)
    SET @DESTLog = @NewPath + @LogFileName;
    DECLARE @FILEPATH nvarchar(1000);
    DECLARE @LOGPATH nvarchar(1000);
    SET @FILEPATH = N'xcopy /Y "' + @SRCData + N'" "' + @NewPath + '"';
    SET @LOGPATH = N'xcopy /Y "' + @SRCLog + N'" "' + @NewPath + '"';
    exec xp_cmdshell @FILEPATH;
    exec xp_cmdshell @LOGPATH;
    EXEC @RC = sp_attach_db @DBName, @DESTData, @DESTLog
    go
    can anyone pls help how to set the db offline. currently  i  stopped the sql server services from services.msc and started the  sql server agent.
    should i stop both services for moving from one drive to another?
    note: I tried teh below solution but this didint work:
    ALTER DATABASE <DBName> SET OFFLINE WITH ROLLBACK IMMEDIATE
    Update:
    now am getting the message :
    Msg 15010, Level 16, State 1, Procedure sp_detach_db, Line 40
    The database 'CMP_143' does not exist. Supply a valid database name. To see available databases, use sys.databases.
    (3 row(s) affected)
    (3 row(s) affected)
    Msg 5120, Level 16, State 101, Line 1
    Unable to open the physical file "D:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\CMP_143.mdf". Operating system error 2: "2(The system cannot find the file specified.)".

    First you should have checked the database mdf/ldf name and location by using the command
    Use CMP_143
    Go
    Sp_helpfile
    Looks like your database CMP_143 was successfully detached but mdf/ldf location or name was different that is why it did not get copied to target location.
    Database is already detached that’s why db offline failed
    Msg 15010, Level 16, State 1, Procedure sp_detach_db, Line 40
    The database 'CMP_143' does not exist. Supply a valid database name. To see available databases, use sys.databases.
    EXEC @RC = sp_attach_db @DBName, @DESTData, @DESTLog
    Attached step is failing as there is no mdf file
    Msg 5120, Level 16, State 101, Line 1
    Unable to open the physical file "D:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\CMP_143.mdf". Operating system error 2: "2(The system cannot find the file specified.)"
    Solution:
    Search for the physical files(mdf/ldf) in the OS and copy to target location and the re-run sp_attach_db with right location and name of mdf/ldf.

  • IDOC to JDBC scenario: Does INSERT command expect a result value?

    Hello,
    we have an IDoc-to-JDBC-scenario configured on our XI 3.0, which uses the INSERT command to put a dataset coming from R/3 into a SQL database. This works fine.
    Now a trigger has been activated on the database, which sets a flag to each dataset after inserting.
    Because of this a system error occurs in the Adapter Engine and I found in the AuditLog (logSQLStatement=true), that the INSERT command is processed correcty, but in the next step an error is shown up: 'SQLServerException. A result set was generated for update.'
    Could it be, that the trigger returns a result value, which can't be handled on the XI ?
    If yes, how can I solve this issue? I have read something about the different methods execute(), executeUpdate() and executeQuery(), but I don't know how and where this has to be configured...
    Thanks in advance,
    Juergen

    Hi Upendra,
    I got some more information from the database adminstrator:
    He used the following command 'exec xp_cmdshell @ExportCmd , no_output'
    whereas @ExportCmd contains the command.
    With the no_output option, the xp_cmdshell does not return a recordset.
    I hope this will be helpful to you.
    Grtz,
    Juergen

  • How to check the given path is existing or not using sp_cmdshell

    Hi All,
       I am passing one path to the stored procedure, before executing code i want to check whether the path is given existing or not .
    By using sp_cmdshell we can know whether files are there are not but in case of my scenario i want to know the directory(folder) is existing or not because the source folder may be blank so it will not get the files there so stored procedure returning the
     File Not found as output.
    following is the code i am trying to retrieve this please suggest any other way to solve it.
    Create table #tableExists  (isValid varchar(255))
    Declare @path varchar(255)='DIR "C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA "/B'
    INSERT INTO #tableExists 
    EXEC xp_cmdshell @path
    select * from #tableExists
    Regards,
    Niraj Sevalkar

    You can try the other two undocumented extended stored procedures as well:
    --EXEC master.dbo.xp_subdirs @pathName
    EXEC Master.dbo.xp_fileexist @pathName
    EXEC Master.dbo.xp_DirTree @pathName,1

  • How to spool the result of an query into a file in sql 2000

    Hi All,
    I have an SQL query which iterates through number of times for checking on some conditions and will return results each time. I wants to save the results into an different xml file each time. I tried using below query:
    exec xp_cmdshell 'bcp "use Mimsadaptorlogs; select top 10 * from log order by logdate" queryout "D:\cdr_cg.xml" -T -c -t,'  ---> Its not working as expected.
    I got the Below output:
    NULL
    Starting copy...
    SQLState = 01000, NativeError = 5701
    Warning = [Microsoft][ODBC SQL Server Driver][SQL Server]Changed database context to 'MIMSAdaptorlogs'.
    NULL
    10 rows copied.
    Network packet size (bytes): 4096
    Clock Time (ms.): total       62
    NULL
    Could you anuone please suggest me on this.......
    Thanks and Regards, Bala

    You will need to write a client program to do this. SQL Server is not intended for writing files. People still do it by calling BCP through xp_cmdshell, but this is a dubious practice. Better is to write a CLR stored procedure for the task. However, you
    are on SQL 2000, and the CLR support was added in SQL 2005. Furthermore, there is no XML type in SQL 2000, and the only way to generate XML is with the FOR XML clause. But this output is not well understood by BCP. Then I try: [code} bcp "SELECT * FROM Northwind..Customers
    FOR XML RAW" queryout slask.bcp -c -T [/code] on SQL 2000, I get [code] 11 rows copied. [/code] which is complete hogwash, because there are 91 rows in that table, and the output should be a single XML document, and the output looks like this: [code] <row
    CustomerID="ALFKI"... Bouchers" City="Marseil... tomerID="DUMON" Company... 0.32.21.21" Fax="40.32.... los Hern ndez" ContactT... n Steel" ContactTitle="... e" ContactTitle="Market... ="Salzburg" PostalCode=... " Phone="(21) 555-3412"... ty="Charleroi" PostalCo...
    <row CustomerID="WARTH"... [/code] I have truncated the output on the right side, but the left side is authentic. It really is that bad.
    Erland Sommarskog, SQL Server MVP, [email protected]

  • XML Column from table extract to Pipe Delimited Text File

    Hi,
    I have an XML column with large data in a Table ( Source SQL server Database).
    I was asked to   extract    XML column to .txt file using SSIS.
    Is it possible to extract xml column with huge data to text file ?
    when I tried,  select XML column from Table in source , I noticed  that Property of column is taken as [DT_NTEXT] . I Converted it to DT_TEXT as Ansi donot support DT_NTEXT.
    Execution method was success but it failed due to trucation. so wondering is there a way to get XML column extracted to Pipe delimited text file?
    Is it advisable to do this ? or IS It Valid to export XML in Pipe Delimited File ?
    Please Kindly advice
    thanks
    kodi

    Are you looking at shredding data within XML nodes and then importing it to text file or are you looking at exporting XML value as is? Also is SSIS a necessity?
    If not, You can simply use T-SQL for this along with bcp for this. just use a query like
    EXEC xp_cmdshell 'bcp "SELECT CAST(XMLColumn AS varchar(max)) AS Column FROM table" queryout <full file path> -c -S <ServerName> -T -t |'
    provided you use trusted connection (windows authentication)
    see
    http://visakhm.blogspot.in/2013/10/bcp-out-custom-format-data-to-flat-file.html
    If you want to shred the data use Xpath functions in the query as below
    http://visakhm.blogspot.in/2012/10/shred-data-as-well-as-metadata-from-xml.html
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • Trying to output to a file

    When I run the below I receive an error
    select * from professionals queryout 'q:\prof.txt'
    Msg 102, Level 15, State 1, Line 1
    Incorrect syntax near 'q:\prof.txt'.

    If you have xp_cmdshell enabled you are ready to export your files:
    EXEC xp_cmdshell 'bcp "select * from professionals" queryout "q:\prof.txt" -T -c -t,'
    More details:
    http://www.mssqltips.com/sqlservertip/1633/simple-way-to-export-sql-server-data-to-text-files/
    If this post answers your query, please click "Mark As Answer" or "Vote as Helpful".

Maybe you are looking for

  • Tcode for list billing for a particular period

    hi gurus I wanted to see particular period's invoices. is there any transaction code for this transaction ? please help out in this regards raj

  • Problem in fetching data

    hi I M FACING STRANGE PROBLEM. WHEN I GIVE SIMPLE "SELECT * FROM TABLE@DBLINK" COMMAND IT GIVES NOT ERROR. ALSO ON THE MOTHER SCHEMA IT RUNS FINE. BUT WHEN I USE THIS COMMAND OVER OTHER DATABASE WITH DBLINK LIKE I MENTIONED HERE BELOW, A VERY STRANGE

  • Problem in Installing Database Instance in R3 system

    Hi, i am installing SAP r/3 installation. I have installed Central Instance Successfully When i am installing DAtabase instance. I am getting the following Error Please help me how to proceed ERROR 2006-11-25 20:47:33 FRF-00007  Unable to open RFC co

  • .kext error message

    I'm getting this message in startup, and occasionally at other times. I'm also getting crashes when the Mac is left to perform a function for a long time, eg a Time Machine backup or large file copy. Not sure if these two problems are related. Can an

  • No Authorization to choose Ibase

    Dear all, We have configured Service Desk in Solman 4.0 support level 9. When we go to the transacation notif_create and while choosing the ibase we get no authorization message. But when I checked Su53, it says authorization successfull. Also I have