EXEC master..xp_cmdshell
Hi:
I have a SSIS package, which, when I execute from Visual Studio it executes fine.
It has about 10 Variables declared, all the 10 variables contain Oracle queries that are set to the Data SOurce in the Data Flow Task.
When I run this package from Visual Studio the package runs fine but when I execute the same package from an SP
Like this...
EXEC master..xp_cmdshell 'dtexec /F "C:\XXX\Integration Services Project1\Integration Services Project1\XXXUsers.dtsx"'
(harcoded the variables for now)
It throws up errors for all the variables declared.. errors are as follows
Error: 2014-08-21 16:47:55.39
Code: 0xC02020F6
Source: PERSON LIST XXX PersonList Data Source [2]
Description: Column "ACTIVE_CARD_NO" cannot convert between unicode and non-unicode string data types.
End Error
Warning: 2014-08-21 16:47:55.40
Code: 0x800470C8
Source: PERSON LIST XXXX PersonList Data Source [2]
Description: The external columns for XXX PersonList Data Source are out of synchronization with the data source columns.
The external column "ACTIVE_CARD_NO" needs to be updated.
End Warning
Error: 2014-08-21 16:47:55.40
Code: 0xC004706B
Source: PERSON LIST SSIS.Pipeline
Description: XXXX PersonList Data Source" failed validation and returned validation status "VS_ISBROKEN".
End Error
The string data from the source is coming as 'Unicode String', I have added a 'Data Conversion' task to convert it to string[DT_STR].
What could be wrong here
Hi Sudhakar,
This issue is more related to SQL Server Integration Services, I will move this thread to SSIS fourm for better support.
If you have any feedback on our support, please click
here.
Best Regards,
Elvis Long
Elvis Long
TechNet Community Support
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:'
ThanksHallo 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) -
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. -
/* This code does not work as echo statement has multiple lines in it*/
SET NOCOUNT ON
DECLARE @cmd VARCHAR(8000)
SELECT @cmd = 'echo
CREATE VIEW dbo.View_1
AS
SELECT Id
FROM dbo.Table_Test
> C:\view.sql'
EXEC master..xp_cmdshell @cmd
I want the above code to work as it is.
/* This code works fine as the echo statement is in a single line*/
SET NOCOUNT ON
DECLARE @cmd VARCHAR(8000)
SELECT @cmd = 'echo CREATE VIEW dbo.View_1 AS SELECT Id FROM dbo.Table_Test > C:\Script\view.sql'
EXEC master..xp_cmdshell @cmdIts not possible. Are you trying to generate the sql scripts to a file?
You can generate the sql's to a file.
Master..xp_cmdshell 'sqlcmd -S ServerName -i f:\dynamic.sql -E>>f:\output.sql'
Is this the same problem you posted earlier as well?
https://social.technet.microsoft.com/Forums/sqlserver/en-US/f9ddd369-f4e2-4622-afbd-607e38a2a6b1/create-sql-files?forum=transactsql
--Prashanth -
Hi,
I have an old SQL 2000 server that uses
xp_cmdshell. Been working fine for years.
Now it comes up with an error
when I run this:
exec master.dbo.xp_cmdshell 'dtsrun -E -Swsisql3 -NImport_APDIST'
I get this error:
Cannot load the DLL ppspps, or one of the DLLs it
references. Reason: 126(The specified module could not be found.).
So in
troubleshooting I run this:
use master
go
sp_helpextendedproc 'xp_cmdshell'
the results:
name dll
xp_cmdshell
ppspps
I can't seem to figure out why the DLL is missing? I searched for
ppspps.dll and is not on the server. Is this even the correct file?
qeqw8Looks something is not what it should be on that server. When I run
EXEC sp_helpextendedproc 'xp_cmdshell'
on SQL 2000, I get:
name dll
xp_cmdshell xplog70.dll
DBCC CHECKDB and DBCC CHECKCATALOG on master could be a start to see whether there is plain corruption.
But I would also look around to see if there are other spooky things.
I guess that you can repair it by dropping and readding xp_cmdshell, but it is not that it is supported - then again, nor is SQL 2000 these days...
Erland Sommarskog, SQL Server MVP, [email protected] -
Problems with xp_cmdshell
Hi!
I am trying to use xp_cmdshell for the first time.
When I run the following command in a cmd window on the server it works. (it just calls a third party tool that takes backups)
"C:\BackupScripts\Backup.bat" "FULL" "SSDBSERV\L008" "MH" "SQL_UAT"
"C:\BackupScripts\Backup.bat" "FULL" "SQL01" "MH" "SQL_UAT"
Now im trying to execute it via sql using xp_cmdshell so im running:
exec master.dbo.xp_cmdshell '"C:\BackupScripts\Backup.bat" "FULL" "SQL01" "MH" "SQLUAT"'
but I get the error:
The system cannot find the path specified.
Does the xp_cmdshell command handle the quotations funny? Am I doing something wrong?
Thanks,
ZoeSorted it!
Just had to double the quotation marks at the start and end
exec master.dbo.xp_cmdshell '""C:\BackupScripts\Backup.bat" "FULL" "SQL01" "MH" "SQLUAT""'
Thanks for all your help!
Zoe -
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
DanI 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] -
Executing an SSIS package from TSQL without using xp_cmdshell?
How can I execute an SSIS package from TSQL without using xp_cmdshell?
I have a web-app which calls some SQL which executes my SSIS package (a DTSX file, but stored in the server). But the security policy for my application won't permit me use to xp_cmdshell.
I want to do this:-
DECLARE @returncode int
EXEC @returncode = xp_cmdshell 'dtexec /sq pkgOne"'
Is there another way for executing a Package without going to the command line (e.g. is there some other system stored proc)?
ThanksWhoa - don't go taking my words as saying "it should work". I never said that - I just said I know less than you :) I'm assuming that since the CLR is .Net, and you can launch a package from .Net code, you may be able to do so from the CLR.
But... I also know that CLR has lots of restrictions on it, and some of those may cause you to be unable to run it from the CLR.
One thing I will say - I've never heard of anyone doing this. That's got to tell you something about:
Whether it can be done at all... although I think I'd have heard/seen something about how it's not possible.
Whether it's a good idea... maybe other routes are less trouble.
Talk to me now on -
Hello All,
Been looking into this for a couple of days, and I keep hitting brick walls, so I'm hoping someone can offer me a bit of inspiration. What I'm trying to do is write a stored procedure that lets the user specify a list of tables, and an output directory, and the SP creates a series of BCP statements that export these tables to comma delimited files.
This wouldn't be too hard, but I need to output the field headings in the first row of the table (and use quotes as text qualifiers). I'm doing this by looping round sys.columns, pulling out all the fieldnames, creating two select statements, and UNION ALL-ing them together. e.g.......
select 'FIELD1','FIELD2','FIELD3','FIELD4'
union all
select field1,field2,field3,field4 from tablename
It all works fine until you try it on a table with a lot of columns. Although you can build a big SQL statement in an NVARCHAR(MAX), BCP only appears to read the first 4000 characters of it, so it fails.
To get round this, I've moved all of the code that builds the big SQL statement to its own stored procedure (i.e. you pass the tablename, and it returns the table with the field names in the first row). Then, I can just call this new SP in my BCP statement, with a couple of parameters.
The problem I'm getting is BCP is complaining saying '[Microsoft][SQL Native Client]BCP host-files must contain at least one column'. I'm setting no count off, and there are no print statements, so I'm assuming this is because the data is getting returned via an exec sp_executesq (although this is a guess). I can't think of a way round this though, as the SQL need to be dynamic.
alter PROCEDURE [dbo].[sp_QBMultiFileExportGetData]
@tablename varchar(100),
@dbname varchar(100)
AS
BEGIN
declare @Execstring as nvarchar(MAX)
declare @currentfieldname as varchar(100)
declare @selectlist as varchar(8000)
declare @fieldnamelist as varchar(8000)
declare @colnames table
columnname varchar(100)
begin
set nocount on
set @execstring='select COLUMN_NAME '+
'from ' + @dbname + '.INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = ''' + @tablename + ''''
insert into @colnames(columnname)
exec sp_executesql @execstring
set @selectlist=''
set @fieldnamelist=''
--Loop through fieldnames, and build two strings
--One for outputting fieldnames and one for selecting the actual data
while exists(select * from @colnames)
begin
select top 1 @currentfieldname=columnname from @colnames
set @selectlist=@selectlist + 'quotename(['+ @currentfieldname + '],char(34)),'
set @fieldnamelist=@fieldnamelist + '''' + @currentfieldname + ''' [' +@currentfieldname + '],'
delete from @colnames where columnname=@currentfieldname
end
--remove last quote
set @selectlist=substring(@selectlist,1,len(@selectlist)-1)
set @fieldnamelist=substring(@fieldnamelist,1,len(@fieldnamelist)-1)
--Built string to execute, with fieldnames, and select fields
set @execstring='select ' + @fieldnamelist + ' union all select ' + @selectlist + ' from ' + @dbname + '..' + @tablename
return exec sp_executesql @execstring
end
END
this returns exactly what I want, but when I try to use it in a BCP statement, I get the error....
i.e.
EXEC master..xp_cmdshell 'bcp "exec QCDev.dbo.sp_QBMultiFileExportGetData ''tablename'',''dbname''" queryout C:\\outputfile.txt -T -t","'
Error = [Microsoft][SQL Native Client]BCP host-files must contain at least one column
Anyone ever tried this before?Hi Guys,
Thanks for the suggestions. I had been trying to avoid temp tables (don't really like them), but I think eventually, they were the only way to go. Unfortunately, this opened a whole can of scoping worms, and after a couple of hours, its all given me a right headache. However, the good news is I've finally got it working as I wanted.
I was finding I was having issues using temp tables, as the tables being used were dynamic, so I would have to create them in a dynamic SQL string, and they weren't propagating upwards from child to parent. I seemed to be getting the same problem using global temporary tables too, although I'm not sure why, as they should have worked They seemed to be out of scope by the time the SP that was calling my sp_QBMultiFileExportGetData tried to output the data. This might possibly have been because BCP wasn't seeing the same scope, but I've not tested it fully (and its very possible I was making a mistake).
The solution was to abandon sp_QBMultiFileExportGetData, and merge the code back into the calling script. However, rather than trying to pass an enormous SQL string to bcp, running it separately with sp_executesql, and dumping the results in a global temp table. Then let bcp just call a 'select * from temptable', to avoid the select statement getting too long. Its not the most elegant solution, but it seems to work fine.
ALTER PROCEDURE [dbo].[sp_QBMultiFileExport]
-- Add the parameters for the stored procedure here
@tablenames varchar(1000), --list of tables to be exported
@outputpath varchar(1000), --output path ***AS SEEN BY THE SERVER, NOT THE CLIENT***
@servername varchar(100), --Server where data resides
@dbname varchar(100), --database name
@delimiter varchar(1) --output delimiter
AS
BEGIN
declare @Execstring as nvarchar(max)
declare @currenttable as varchar(100)
declare @colnames table
columnname varchar(100)
declare @currentfieldname as varchar(100)
declare @selectlist as varchar(max)
declare @fieldnamelist as varchar(max)
--Get rid of CRLFs in the tablenames parameter
set @tablenames=replace(@tablenames,char(10),'')
set @tablenames=replace(@tablenames,char(13),'')
--add extra comma to the end of the list (needed later for consistency)
set @tablenames=@tablenames+','
--Get first table in the list
set @currenttable=substring(@tablenames,1,charindex(',',@tablenames)-1)
while @tablenames<>''
begin
--Get a list of fieldnames from syscols
insert into @colnames(columnname)
select COLUMN_NAME
from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = @currenttable
set @selectlist=''
set @fieldnamelist=''
while exists(select * from @colnames)
begin
--get first column name
select top 1 @currentfieldname=columnname from @colnames
--add to select statement lists
set @selectlist=@selectlist + 'quotename(['+ @currentfieldname + '],char(34)),'
set @fieldnamelist=@fieldnamelist + '''' + @currentfieldname + ''' [' +@currentfieldname + '],'
--remove column from temptable
delete from @colnames where columnname=@currentfieldname
end
--remove last quote from field lists
set @selectlist=substring(@selectlist,1,len(@selectlist)-1)
set @fieldnamelist=substring(@fieldnamelist,1,len(@fieldnamelist)-1)
--check for temp table, and drop if necessary
IF object_id('tempdb..##MultiFileExportTempTable') IS NOT NULL
BEGIN
DROP TABLE ##MultiFileExportTempTable
END
--Build list of fieldnames, and select list, unioned together
--and put the results in temptable
set @execstring='select ' + @fieldnamelist + ' into ##MultiFileExportTempTable union all select ' + @selectlist + ' from ' + @dbname + '..' + @currenttable
exec sp_executesql @execstring
--get BCP to pull data back from ##temptable, and dump in file
set @execstring='EXEC master..xp_cmdshell ''bcp "select * from ##MultiFileExportTempTable" queryout ' + @outputpath + '\' + @currenttable + '.txt' + ' -c -T -t"' + @delimiter + '"'''
exec sp_executesql @execstring
--drop tablename from list
set @tablenames=replace(@tablenames,@currenttable + ',','')
--if tablenames list is not empty, get the next one
if @tablenames<>''
set @currenttable=substring(@tablenames,1,charindex(',',@tablenames)-1)
else
set @currenttable=''
end
IF object_id('tempdb..##MultiFileExportTempTable') IS NOT NULL
BEGIN
DROP TABLE ##MultiFileExportTempTable
END
END
So, you call this with...
exec dbo.[sp_QBMultiFileExport] 'table1,table2,table3',filepath,servername,dbname,delimiter
...and it creates delimited files called table1.txt, table2.txt and table3.txt in the specified folder, with field headings and text qualifiers.
Many thanks for all your suggestions -
How to export data with column headers in sql server 2008 with bcp command?
Hi all,
I want know "how to export data with column headers in sql server 2008 with bcp command", I know how to import data with import and export wizard. when i
am trying to import data with bcp command data has been copied but column names are not came.
I am using the below query:-
EXEC master..xp_cmdshell
'BCP "SELECT * FROM [tempdb].[dbo].[VBAS_ErrorLog] " QUERYOUT "D:\Temp\SQLServer.log" -c -t , -T -S SERVER-A'
Thanks,
SAAD.Hi All,
I have done as per your suggestion but here i have face the below problem, in print statment it give correct query, in EXEC ( EXEC master..xp_cmdshell @BCPCMD) it was displayed error message like below
DECLARE @BCPCMD
nvarchar(4000)
DECLARE @BCPCMD1
nvarchar(4000)
DECLARE @BCPCMD2
nvarchar(4000)
DECLARE @SQLEXPRESS
varchar(50)
DECLARE @filepath
nvarchar(150),@SQLServer
varchar(50)
SET @filepath
= N'"D:\Temp\LDH_SQLErrorlog_'+CAST(YEAR(GETDATE())
as varchar(4))
+RIGHT('00'+CAST(MONTH(GETDATE())
as varchar(2)),2)
+RIGHT('00'+CAST(DAY(GETDATE())
as varchar(2)),2)+'.log" '
Set @SQLServer
=(SELECT
@@SERVERNAME)
SELECT @BCPCMD1
= '''BCP "SELECT
* FROM [tempdb].[dbo].[wErrorLog] " QUERYOUT '
SELECT @BCPCMD2
= '-c -t , -T -S '
+ @SQLServer +
SET @BCPCMD
= @BCPCMD1+ @filepath
+ @BCPCMD2
Print @BCPCMD
-- Print out below
'BCP "SELECT
* FROM [tempdb].[dbo].[wErrorLog] " QUERYOUT "D:\Temp\LDH_SQLErrorlog_20130313.log" -c -t , -T -S servername'
EXEC
master..xp_cmdshell
@BCPCMD
''BCP' is not recognized as an internal or external command,
operable program or batch file.
NULL
if i copy the print ourt put like below and excecute the CMD it was working fine, could you please suggest me what is the problem in above query.
EXEC
master..xp_cmdshell
'BCP "SELECT * FROM
[tempdb].[dbo].[wErrorLog] " QUERYOUT "D:\Temp\LDH_SQLErrorlog_20130313.log" -c -t , -T -S servername '
Thanks, SAAD. -
Need help to create file with name and current time stamp.
I need to create .xlsx file exporting data from sql database and file name would be 'FileName' and current yyyymmdd.
I'm trying to use following code but it's keep saying incorrect syntax near "+".
EXEC p_CreateExcel 'sql64', 'NewFile', '\\hrfile1\Shared\Buying Report\NewFile'
+ CAST(YEAR(CURRENT_TIMESTAMP) AS VARCHAR)
+ RIGHT('00'+CAST(MONTH(CURRENT_TIMESTAMP) AS VARCHAR),2)
+ RIGHT('00'+CAST(DAY(CURRENT_TIMESTAMP) AS VARCHAR),2)+'.xlsx'This is what I have on EXEC p_CreateExcel
USE [XePro01]
GO
/****** Object: StoredProcedure [dbo].[p_CreateExcel] Script Date: 02/26/2015 11:27:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER procedure [dbo].[p_CreateExcel]
@db_name varchar(100),
@table_name varchar(100),
@file_name varchar(100)
as
--Generate column names as a recordset
declare @columns varchar(8000), @sql varchar(8000), @data_file varchar(100)
select
@columns=coalesce(@columns+',','')+column_name+' as '+column_name
from
information_schema.columns
where
table_name=@table_name
select @columns=''''''+replace(replace(@columns,' as ',''''' as '),',',',''''')
--Create a dummy file to have actual data
select @data_file=substring(@file_name,1,len(@file_name)-charindex('\',reverse(@file_name)))+'\data_file.xls'
--Generate column names in the passed EXCEL file
set @sql='exec master..xp_cmdshell ''bcp "set fmtonly off select * from (select '+@columns+') as t" queryout "'+@file_name+'" -c -t, -T -S'''
exec(@sql)
--Generate data in the dummy file
set @sql='exec master..xp_cmdshell ''bcp "set fmtonly off select * from XeProgst01.dbo.'+@table_name+'" queryout "'+@data_file+'" -c -t, -T -S'''
exec(@sql)
--Copy dummy file to passed EXCEL file
set @sql= 'exec master..xp_cmdshell ''type '+@data_file+' >> '+@file_name+''''
exec(@sql)
--Delete dummy file
set @sql= 'exec master..xp_cmdshell ''del '+@data_file+''''
exec(@sql)
GO -
How to delete the Folder from sql server 2008
Hi all,
I was trying to delete the folder from sql server 2008 with the below script
DECLARE @path VARCHAR(256) -- path for backup files
DECLARE @cmd VARCHAR(8000)
DECLARE @folderName VARCHAR(256) -- filename for backup
SET @folderName = + (CONVERT(varchar(10), GETDATE()-7, 112)) -- 7 days back date folder name
SET @path = 'I:\Backup_Test\' + @folderName -- Folder path
SET @cmd = 'del ' + @path -- Delete
EXEC master..xp_cmdshell @cmd
--Print @cmd
This is not working it was asking the Confirmation (I:\Backup_Test\20100629\*, Are you sure (Y/N)? ) what will i do to the delete the folder.
Thanks,
Prasad R.I would notice you that T-SQL does not play well to do things like that. Do not you want using .net language to delete folders?
Old method is
declare @HR int, @CFOLDER varchar(255),@FSO int
set @CFOLDER='D:\folder\'
EXEC @HR = sp_OACreate 'Scripting.FileSystemObject', @FSO OUT
EXEC @HR = sp_OAMethod @FSO, null, 'DeleteFolder', @CFOLDER
Now regarding to your second question please examine xp_fileexist system stored procedure
CREATE FUNCTION dbo.fn_file_exists(@filename VARCHAR(300))
RETURNS INT
AS
BEGIN
DECLARE @file_exists AS INT
EXEC master..xp_fileexist @filename, @file_exists OUTPUT
RETURN @file_exists
END
GO
-- test
SELECT dbo.fn_file_exists('c:\a.txt')
Best Regards, Uri Dimant SQL Server MVP http://dimantdatabasesolutions.blogspot.com/ http://sqlblog.com/blogs/uri_dimant/ -
I am unable to succeed with sql agent job, I am trying to execute the SSIS package through sql agent job by ticking 32 bit runtime check box in 64 bit machine , even it does not worked..
could any one helpme on this?
Source: Excel Load Connection manager "Excel Connection Manager"
Description: SSIS Error Code DTS_E_OLEDBERROR. An OLE DB error has occurred. Error code: 0x80040154. An OLE DB record is available. Source: "Microsoft OLE DB Service Components" Hresult: 0x80040154 Description: "Class
not registered". End Error TS_E_CANNOTACQUIRECONNECTIONFROMCONNECTIONMANAGER. The AcquireConnection method call to the connection manager "Excel Connection Manager" failed with error code 0xC0202009. There may be error
messages posted before this with more information on why the AcquireConnection method call failed. End... The package execution fa... The step failed.Hello Keerthi,
Can you please modify settings and set delay validation for Excel connection manager? I think its validating connection and failing because it might be picking that from some variable.
Alternatively, please run package using below and see what happens.
EXEC master..xp_cmdshell 'DTEXEC.exe /SQL "Folder\Package" /SERVER Servername'
I will recommend you to follow steps in below link.
http://www.sqlhammer.com/blog/running-ssis-packages-in-32-bit/
Regards,
Vishal Patel
Blog: http://vspatel.co.uk
Site: http://lehrity.com -
DECLARE @TenantId UNIQUEIDENTIFIER ='A79ED820-2E5E-4A9D-B930-B7597DC97081'
DECLARE @BusinessName VARCHAR(200)
declare @line varchar(255) =''
declare @path varchar(255)=''
declare @command varchar(255)=''
DECLARE @folderSizeGB decimal (16,8) = 0
DECLARE @AttachmentDiscSpaceUsed decimal (16,8) = 0
-- Code to calculate folder size in GB BEGINs
IF OBJECT_ID('tempdb..#temp') IS NOT NULL
drop table #temp
create table #temp (line varchar(255))
--set @path = '\\ewp-dev18\\c$\\Attachments\\' + CONVERT(varchar(50),@tenantId)
set @path = '-S ewp-dev18 -E -i ewp-dev18\\c$\\Attachments\\' + CONVERT(varchar(50),@tenantId)
set @command = 'dir "' + @path +'"'
insert into #temp
exec master.dbo.xp_cmdshell @command
select
@line=
ltrim(replace(substring(line, charindex(')', line)+1,
len(line)), ',', ''))
from #temp where line like '%File(s)%bytes'
SET @line=
(Case WHEN @line IS NULL or @line ='' THEN '0' ELSE @line END)
set @folderSizeGB = Cast(Replace(@line,'bytes', '') as decimal)/1073741824
if (@folderSizeGB is null )
set @folderSizeGB =0
SET @AttachmentDiscSpaceUsed = @folderSizeGB
SET @path=''
SET @command=''
SET @line=0
-- Drop #temp table
IF OBJECT_ID('tempdb..#temp') IS NOT NULL
drop table #temp
-- Code to calculate folder size in GB ENDs
hello RSingh,
Once again thanks for your cooperation,
I applied the script you posted, but it is not giving me the size of the folder which is located at a remote machine. Please note the " I need to calculate the size of the folder which is located at a remote machine".and when i applied its path in your script,
it raises "Access is denied" error message.
My path is - '\\ewp-dev18\c$\Attachments'
EXEC getFileProperties '\\ewp-dev18\c$\Attachments'
and this folder does not have any sub folders, it contains only some txt files, image files or some doc files. so no issue of sub folder.
and about my remote server 'ewp-dev18', i have all access and rights, but still raising "Access is denied". why?
do i need to pass any login credential with it ??? -
How to replace a character at a random position of a column in SQL Server 2000?
Hello everyone,
I'm trying to export the data of a table into a flat file. However, when I try to export it, a column which has a specific character (".") is being loaded as a new column into the file rather than the same column.
Here is the DDL/DML:
CREATE TABLE [dbo].[EXT_Name](
[A_Name] [VARCHAR](4),
[U_Name] [VARCHAR](256),
[U_Desc] [VARCHAR](256),
[Acc_Desc] [VARCHAR](256),
[S_Type] [VARCHAR](50))
Its just that's it. No more Keys and Indexes on this table.
Here is the bcp command I'm running:
EXEC [master].[dbo].[xp_cmdshell] 'bcp "SELECT * FROM [dbo].[Ext_Name]" queryout C:\Data\Ext_Name.dat -c -t, -T -S'
Data:
GEHG,/User/Personal/Project/Click.do,Search for User Project.,See Summary,Summaries
GEHG,/User/Personal/Project/Click.do,Search for User Project.Detail,null,Summaries
Instead for the data to be loaded as the above, its loading into the file as
GEHG,/User/Personal/Project/Click.do,Search for User Project.,See Summary,Summaries
GEHG,/User/Personal/Project/Click.do,Search for User Project.Detail
,null,Summaries
This issue occurs only when [Acc_Desc] column has the "." character in between the string. Could experts in this forum help me please?
Thank you,
Bangaaram
Known is a DROP, Unknown is an OCEAN.That is most likely not your problem. Your problem is most likely the source data has a CR and/or LF after it in the database.
Run this to remove them from Acc_Desc:
UPDATE [dbo].[EXT_Name]
SET [Acc_Desc] = REPLACE(REPLACE([Acc_Desc],CHAR(13),''),CHAR(10),'')
Perfect! Thank you Tom :)
Known is a DROP, Unknown is an OCEAN.
Maybe you are looking for
-
Hi, I need some help!! In my actual proyect, we are using DS "0FI_GL_10", which has a AIED delta process. Someone knows, if this configuration could carry on any type of extraction problem, such as a duplication of data in BI? This is what it is happ
-
I have an instrument from Reason rewired into Logic and it works fine. But when I select a new track in Logic (eg piano), my instrument from Reason plays in addition to the piano. I've had this happen in the past but can't remember what to do! Is it
-
Hello, in our WAS 6.20 environment (running on AIX) we used an external IGS (Internet Graphics Server) on a Windows machine. Now we've upgraded to NW2004s and we want to use the internal IGS. Everything's running fine but I'm wondering wheter (and HO
-
RT safemode (software error)
Hi, I've developed quite a large bit of software. One of the software modules runs on a RT Gateway. I usually let the code run for a few days to test it. Although twice now it it has crashed after about a day and in MAX I see the RT device is in Safe
-
What default font is being used for skin tooltips in captivate 6.0
What default font is being used for skin tooltips in captivate 6.0