【发布时间】:2012-06-12 10:47:31
【问题描述】:
所有,我需要将一个大型 SQL 表中的数据集写入 .txt 文件。为此,我选择使用 xp_cmdshell。我用来创建 Data.txt 文件的查询是
declare @sql varchar(8000)
select @sql = 'bcp "SELECT /*Lots of field names here*/ ' +
'FROM [SomeDatabase]..TableName WHERE /*Some Long Where Clause*/" ' +
'queryout "M:\\SomeDir\\SomeOtherDirectory\\Data.txt" -c -t -T -S' + @@servername
exec master..xp_cmdshell @sql
我遇到的问题是我使用的SELECT 查询超出了命令行强加的 1024 个字符限制。为了解决这个问题,我决定尝试使用sqlcmd 尝试从文件中执行我需要的 SQL 查询,从而消除查询长度的错误。我尝试了以下查询
DECLARE @DatabaseName VARCHAR(255)
DECLARE @cmd VARCHAR(8000)
SET @DatabaseName = 'SomeDatabase'
SET @CMD = 'SQLCMD -E -S (localhost) -d ' + @DBName +
'i "M:\\SomeDir\\SomeOtherDirectory\\tmpTestQuery.sql"'
EXEC master..xp_cmdshell @CMD
其中 'tmpTestQuery.sql' 包含我要执行的长查询,但出现以下错误
HResult 0x2AF9, Level 16, State 1
TCP Provider: No such host is known.
NULL
Sqlcmd: Error: Microsoft SQL Server Native Client 10.0 : A network-related or instance-
specific error has occurred while establishing a connection to SQL Server.
Server is not found or not accessible. Check if instance name is correct and
if SQL Server is configured to allow remote connections.
For more information see SQL Server Books Online..
Sqlcmd: Error: Microsoft SQL Server Native Client 10.0 : Login timeout expired.
NULL
我已启用远程连接。
我想知道我做错了什么,是否有其他方法可以解决我在使用 xp_cmdshell 时遇到的查询长度问题?
感谢您的宝贵时间。
注意。这个查询最终会从 C# 调用,所以计划是将很长的查询写入一个临时的 .txt 文件,使用概述的方法执行它,完成后删除。
【问题讨论】:
标签: sql tsql xp-cmdshell