SqlServer之xp_cmdshell_使用以及配置


對大數據量導入導出就好的辦法,就是在命令行中使用bcp命令來導入導出數據。

/*MSsql2005以上 如何啟用xp_cmdshell
默認情況下,sql server2005以上安裝完后,xp_cmdshell是禁用的(可能是安全考慮),如果要使用它,可按以下步驟
*/

-- 允許配置高級選項
EXEC sp_configure 'show advanced options', 1
GO

-- 啟用xp_cmdshell
EXEC sp_configure 'xp_cmdshell', 1
GO

/*執行內容

-- 把 YTHR 中的Employee 表的數據導出到D:\estTemp.xls(或d:\TEST.txt) , 導出以后會覆蓋原有文件的內容

-- 設置字段分隔符和行分隔符(-c -t"," -r"\n"),不想輸入字段類型等請配合-c一起使用

exec master..xp_cmdshell'bcp " select * from [Test].[dbo].[employee]" queryout d:\TEST.txt -c -T -t" , " -r"\n"'

exec master..xp_cmdshell'bcp " select DEPTID AS 數量,salary as 單價,cood as 名稱 from [Test].[dbo].[employee]" queryout d:\estTemp.xls -c -T -q'

--1.把表字段轉為中文和數據一起導出

go
CREATE TABLE product(productid int,productname varchar(50)) 
insert into product
select 1,'衣服' union
select 2,'帽子' union
select 3,'鞋子' union
select 4,'褲子' union
select 5,'襪子'


declare @count int,@i int,@name varchar(50),@t int
declare @sql varchar(500)

declare @DbTable varchar(100)
SET @DbTable = 'tempTable'
IF EXISTS (SELECT 1
FROM sysobjects
WHERE name = @DbTable
AND TYPE = 'u')
begin
PRINT 'EXISTS '
end;
ELSE
begin
exec('CREATE TABLE tempTable(id int default(''1''))')
exec('insert into tempTable values(''1'')')
PRINT 'NOT EXISTS '
end;

select name,colid from syscolumns where id=object_id('product')
select @count= COUNT(*) from syscolumns where id=object_id('product')
set @i=@count
if @count>0
begin
while @i>0
begin
select @name=name from syscolumns where id=object_id('product') and colid=@i
select @t=count(*) from syscolumns where id=object_id('temptable') and name=@name
if @t=0
begin
set @sql= 'alter table temptable add'+' ' + @name +' ' +'varchar(50)';
print (@sql)
exec(@sql)
set @i=@i-1
--exec(@sql)
--update tempTable set @name="'"+@name+"'" where id='1'
set @sql='update tempTable set ' +@name+'= '''+@name+''' where id=''1'''
print (@sql)
exec(@sql)
end
else
begin
print '123'
return;
end
end
set @count=@count-1
begin
exec master..xp_cmdshell'bcp "select CASE when productid=''productid'' then ''數量'' END,CASE when productname=''productname'' then ''名稱'' END from [Test].[dbo].[tempTable] union all select ltrim(productid) as productid,productname from [Test].[dbo].[product]" queryout d:\estTemp888.xls -c -T -q'
end;
end;

 -- 2.把表字段內容和數據一起導出

declare @sql varchar(100)

select @sql=isnull(@sql+',''','''')+name+'''' from syscolumns where id=object_id('product')

exec('select '+@sql+' union all select ltrim(productid),productname from product')

*/

--用完后,要記得將xp_cmdshell禁用(出於安全考慮)

-- 禁用xp_cmdshell
EXEC sp_configure 'xp_cmdshell', 0
GO

 

遇見的錯誤:

1、發生以下錯誤:
[Error][Microsoft][Native]Error = [Microsoft][SQL Native Client]無法打開 BCP 主數據文件

使用如下命令:
EXEC xp_cmdshell 'ECHO %USERDOMAIN%\%USERNAME%'
返回 :NT AUTHORITY\NETWORK SERVICE

然后在配置管理器(configuration manager)里面的SQL server2005服務里打開,看到登陸內置賬號為Network service,
改成local system問題解決。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM