我必须一直将查询导出到平面文件中,所以这是我的解决方案。基本上我创建了一个具有查询(记得放入表全名),文件名,目录路径作为参数的过程。值用“|”分隔 默认情况下,但您可以更改它..
不知道这些是否是最佳实践,它对我有用,安全性不是我正在使用的数据库的问题。
BCP 实用程序几乎可以自己解决问题。在创建过程之前,请确保设置正确的权限:this和this。
CREATE PROCEDURE [dbo].[export_table]
@query VARCHAR(8000)
,@out_file VARCHAR(8000)
,@out_dir VARCHAR(8000)
AS
BEGIN
DECLARE @temp NVARCHAR(4000)
DECLARE @query_body VARCHAR(8000)
DECLARE @header VARCHAR(8000)
DECLARE @full_header VARCHAR(8000)
DECLARE @copy VARCHAR(8000)
DECLARE @del VARCHAR(8000)
DECLARE @del1 VARCHAR(8000)
-- CREATE AND EXPORT BODY
-- drop temp table (when running procedure in same instance)
IF OBJECT_ID('tempdb..##temp') IS NOT NULL
DROP TABLE ##temp
-- populate temp with just 1 line so we can take out the header
SET @temp = 'SELECT TOP 1 * INTO ##temp FROM (' + COALESCE(@query,'') + ') a'
-- set up the bcp query removing idents so you dont have to write the query in one line
SET @query_body = 'bcp "' + COALESCE(@query,'') + '" queryout ' + @out_dir + 'qBody.txt -CACP -T -c -t"|" '
SET @query_body = REPLACE(REPLACE(@query_body, CHAR(13), ' '), CHAR(10), ' ')
EXECUTE sp_executesql @temp
EXEC master..xp_cmdshell @query_body
-- CREATE AND EXPORT HEADER
-- set the header using system tables and
-- temp table previously created (alias = name) and use bcp to expor the header
SELECT @header =
COALESCE(@header + ''', ', '') + '''' + name
FROM (
SELECT name
FROM tempdb.sys.columns
WHERE
object_id = object_id('tempdb..##temp')
) b
SET @header = @header + ''''
SET @full_header = 'bcp "select '+ @header +'" queryout ' + @out_dir + 'qHeader.txt -CACP -T -c -t"|" '
-- COPY NEW FILE FROM HEADER AND BODY AND DELETE USED FILES (USING WINDOWS CMD)
SET @copy = 'copy /b "' + @out_dir + 'qHeader.txt" + "' + @out_dir + 'qBody.txt" "' + @out_dir + @out_file + '.txt"'
SET @del = 'del "' + @out_dir + 'qHeader.txt"'
SET @del1 = 'del "' + @out_dir + 'qBody.txt"'
EXEC master..xp_cmdshell @full_header
EXEC master..xp_cmdshell @copy
EXEC master..xp_cmdshell @del
EXEC master..xp_cmdshell @del1
END
GO
-- EXEMAPLE OF USAGE
exec export_table
'select
column1
,column2 as ''escape_quotes''
from cnes.dbo.stg_vinculo'
,'file_name'
,'C:\'