尝试根据 SSMS 2014 中的查询结果创建制表符分隔的 TXT 文件

Trying to create tab delimited TXT file from query results in SSMS 2014

我正在尝试将我的 SSMS 2014 查询结果导出到固定长度的 .txt 文件,但我不确定如何处理其中一个列中的硬编码 (-1) 值。

任何 help/direction 将不胜感激。这是我的第一次尝试,但我无法克服这个错误。谢谢

这里是错误:

Msg 102, Level 15, State 1, Line 3
Incorrect syntax near '-'.

代码如下:

xp_cmdshell 'bcp
"SELECT DISTINCT 
    LEFT(LTRIM(RTRIM('**-1**')), 2) as 'school key', 
    LEFT(LTRIM(RTRIM('1')), 1) as 'district key', 
    LEFT(SPACE(1), 1), 
    LEFT(LTRIM(RTRIM('1')), 1) as 'district wide vendor', 
    LEFT(SPACE(1), 1), 
    LEFT(LTRIM(RTRIM(a_vendor_name)), 30) as name, 
    LEFT(LTRIM(RTRIM(v_vend_address1)), 30) as addr1, 
    LEFT(LTRIM(RTRIM(v_vend_address2)), 30) as addr2, 
    LEFT(LTRIM(RTRIM(v_vend_city)), 25) as city, 
    LEFT(LTRIM(RTRIM(v_vend_state)), 2) as st, 
    LEFT(LTRIM(RTRIM(v_vend_zip)), 10) as zip, 
    LEFT(LTRIM(RTRIM(v_contact1_phone)), 14) as phone, 
    LEFT(LTRIM(RTRIM(v_contact1_fax)), 14) as fax, 
    LEFT(LTRIM(RTRIM(v_vend_status)), 1) as 'status', 
    CASE 
        WHEN LEFT(LTRIM(RTRIM(v_1099_vendor)), 1) = 'Y' THEN '1' ELSE '0' 
    END as irs1099, 
    LEFT(SPACE(1), 1), 
    LEFT(SPACE(10), 10) as tax_id, 
    LEFT(SPACE(6), 6) as vcode, 
    LEFT(LTRIM(RTRIM(v_email_addrs)), 50) as email, 
    LEFT(SPACE(9), 9) as ssn, 
    LEFT(SPACE(20), 20) as comment, 
    LEFT(LTRIM(RTRIM(vr_vend_seq_addr1)), 30) as poaddr1, 
    LEFT(LTRIM(RTRIM(vr_vend_seq_addr2)), 30) as poaddr2, 
    LEFT(LTRIM(RTRIM(vr_vend_seq_city)), 25) as pocity, 
    LEFT(LTRIM(RTRIM(vr_vend_seq_state)), 2) as post, 
    LEFT(LTRIM(RTRIM(vr_vend_seq_zip)), 10) as pozip, 
    LEFT(LTRIM(CONCAT('MUNIS', SPACE(5))), 10) as createdBy, 
    LEFT(LTRIM(RTRIM(REPLACE(CONVERT(varchar(10), getdate(), 101), '/', ''))), 8)  as strDate,
    CASE 
        WHEN LTRIM(RTRIM(a_vendor_remit_seq)) > 0 THEN LEFT(LTRIM(RTRIM(CONCAT(a_vendor_number, a_vendor_remit_seq))), 20) ELSE LEFT(LTRIM(RTRIM(a_vendor_number)), 20) 
    END as covennbr, 
    LEFT(LTRIM(RTRIM(v_dba)), 30) as dba
FROM dbo.vend_table
WHERE v_vend_status = 'A'
AND v_general_type IN ('', '1', '2', '7', '13', '15', '19')" queryout "C:\temp\testTabDelimitedFile.txt -T'

您正在用单引号封装您的 xp_cmdshell 命令,同时还在您的值周围使用单引号。

例如:

xp_cmdshell 'bcp
"SELECT DISTINCT 
    LEFT(LTRIM(RTRIM('**-1**')), 2) as 'school key',
                     ^      ^          ^          ^

因此,你会得到 "incorrect syntax near '-'",因为 xp_cmdshell 认为 **-1** 与你传递的字符串是分开的。

我认为您可以转义单引号 (\')。