你能否告诉我为什么下面的sql有问题。
如果我运行这部分:
Select SmsSCh_ID AS "@Name", CONVERT(CHAR(10), SmsSCh_Scheduledate, 101)
+ ' ' + LTRIM(RIGHT(CONVERT(CHAR(20), SmsSCh_Scheduledate, 20), 10)) AS "@Time" from Prj_SmsSch
for XML path ('Task'), ROOT('appSchedule')
我得到了正确的结果,但当我把它放在代码中,所以我可以将xml导出到文件中,我得到错误。
这是我的完整代码:
DECLARE
@FileName VARCHAR(50),
@SQLCmd VARCHAR(500)
select
@FileName = 'C:\iman\SampleXMLOutput1.xml'
--in this command, we are making sure there is only one ROOT node
SELECT @SQLCmd = 'bcp '
+ '"Select SmsSCh_ID AS "@Name", CONVERT(CHAR(10), SmsSCh_Scheduledate, 101)
+ ' ' + LTRIM(RIGHT(CONVERT(CHAR(20), SmsSCh_Scheduledate, 20), 10)) AS "@Time" from Prj_SmsSch'
+ ' for XML path ('Task'), ROOT('appSchedule')'"'
+ ' queryout '
+ @FileName
+ ' -w -T -S' + @@SERVERNAME
-- display command, for visual check
SELECT @SQLCmd AS 'Command to execute'
-- create the XML file
EXECUTE master..xp_cmdshell @SQLCmd
我认为可能的问题是'在@SQLCmd里面。 错误:
Msg 102, Level 15, State 1, Line 13
Incorrect syntax near ' + LTRIM(RIGHT(CONVERT(CHAR(20), SmsSCh_Scheduledate, 20), 10)) AS "@Time" from Prj_SmsSch'.
Msg 103, Level 15, State 4, Line 14
The identifier that starts with ''
+ ' queryout '
+ @FileName
+ ' -w -T -S' + @@SERVERNAME
' is too long. Maximum length is 128.
Msg 105, Level 15, State 1, Line 14
Unclosed quotation mark after the character string ''
+ ' queryout '
+ @FileName
+ ' -w -T -S' + @@SERVERNAME
'.
感谢您的帮助
答案 0 :(得分:1)
试试这个:
你搞砸了内心的引语。它们必须加倍,因为它们在字符串中。此外,我将AS "@name"
替换为AS [@name]
,因为括号不需要转义。在你的ROOT
声明之后,有一个引用很多......无法测试它,希望这有效:
DECLARE
@FileName VARCHAR(50),
@SQLCmd VARCHAR(500)
select
@FileName = 'C:\iman\SampleXMLOutput1.xml'
--in this command, we are making sure there is only one ROOT node
SELECT @SQLCmd = 'bcp '
+ '"Select SmsSCh_ID AS [@Name] '
+ ',CONVERT(CHAR(10), SmsSCh_Scheduledate, 101) '
+ ' + '' '' + LTRIM(RIGHT(CONVERT(CHAR(20), SmsSCh_Scheduledate, 20), 10)) AS [@Time] '
+ 'from Prj_SmsSch for XML path (''Task''), ROOT(''appSchedule'')"'
+ ' queryout '
+ @FileName
+ ' -w -T -S ' + @@SERVERNAME
-- display command, for visual check
SELECT @SQLCmd AS 'Command to execute'
-- create the XML file
EXECUTE master..xp_cmdshell @SQLCmd