2012-10-17 54 views
0

我想從一個標量結果發送到一個文本文件中的文本文件,發送查詢結果到SqlServer中

我的代碼看起來像這樣

DECLARE @test varchar(10) 

SET @test='This is sample text' 

EXEC master..xp_cmdshell'bcp ' + @test + ' queryout "D:\sample.txt" -S LocalHost -U 
sa -P 123 -c -T -t' 

但這正顯示出以下錯誤

output 
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] 
NULL 

不知道如何給格式BCP命令 請任意一個幫助分配標變量值。

並以這種方式嘗試也

Create table #sample 
    (
    productid int 
) 

    Insert into #sample(productid) values(1001098) 

    EXEC master..xp_cmdshell'bcp "select * from #sample" queryout "D:\sample.txt" -S 
    LocalHost -U sa -P 123 -c -T -t' 

它給出的錯誤,那是

#sample does not exist (in bcp command line) 

任何一個可以請解決這個問題。 在此先感謝。

+0

把所有的SQL爲傳遞給BCP的字符串;如果在其他地方定義了#sample,則它不可用 –

+0

請給我一個將字符串傳遞到bcp命令的語法。提前致謝。 – Mahe

回答

0

首先,臨時表綁定到作用域,因此不能用於不同的進程ID。

但是,您可以聲明一個全局臨時表(確保後來刪除它,並確保使用非常具體的名稱以確保您不會干擾其他一些代碼)。

爲此,您只需在表名中加倍「#」。

if object_ID('tempdb..##sample') is not null 
    drop table ##sample 

Create table ##sample 
(
productid int 
) 

Insert into ##sample(productid) values(1001098) 

然後你所要做的就是輸出。

EXEC master..xp_cmdshell'bcp "select * from ##sample" queryout "d:\sample.txt" -w -U sa -P 123 -S server_name\instance_name' 

正如你所看到的,我也改變了幾個開關。 我發現最好使用-w來生成ansi字符,所以我刪除了-c。 -T用於可信連接,但由於您提供了用戶名和密碼,因此您不需要它。

然後你應該沒問題。

0

測試此:

EXEC xp_cmdshell 'bcp "SELECT *FROM [YOURDATABASE].[dbo].[YOURTABLE]" queryout "f:\newOUTPUT.txt" -S DESKTOP-A5CFJSH\MSSQLSERVER1 -UYOURUSERNAME -PYOURPASSWORD -n ' 
相關問題