【问题标题】:Send Query result into a Text file in SqlServer将查询结果发送到 Sql Server 中的文本文件中
【发布时间】:2015-12-06 13:33:28
【问题描述】:

我想将标量变量的结果发送到文本文件中,

我的代码是这样的

 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) 

谁能解决这个问题。 提前致谢。

【问题讨论】:

  • 把所有的sql放到传递给bcp的字符串中; #sample 如果在别处定义,则不可用
  • 您能否给我将字符串传递给 bcp 命令的语法。提前致谢。

标签: sql-server


【解决方案1】:

首先,临时表绑定到范围,因此不能在不同的进程 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 用于信任连接,但由于您提供了用户名和密码,因此您不需要它。

那你应该没事。

【讨论】:

    【解决方案2】:

    测试一下:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-11
      • 2010-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多