要在Excel上写入SQL的输出在标准路径中

时间:2017-08-15 11:57:22

标签: sql sql-server sql-server-2012

我正在尝试将SQL查询的输出保存到Excel并保存在标准路径中。我使用OPENROWSET来编写输出。

但是我收到了这个错误:

  

'飞利浦'附近的语法不正确。

请分享您宝贵的建议。

INSERT INTO OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
                       'Excel 8.0;Database=C:\testing.xls;', 
       'DECLARE @VPTVARCHAR(24) SET @VPT= 'Philips'
        DECLARE @DAYS INT SET @DAYS = -30   

        SELECT * 
        INTO #XTP1 
        FROM (SELECT DISTINCT 'START' AS DTT, DATEADD(D,@DAYS,DATEACTIONED) AS DT 
              FROM REPORTS
              WHERE VPT = @VPT          
              UNION             
              SELECT DISTINCT 'CHANGE' AS DTT, DATEACTIONED AS DT  
              FROM REPORTS
              WHERE VPT = @VPT          
              UNION             
              SELECT 'END' AS DTT, DATEADD(dd, -1, DATEDIFF(dd, 0, GETDATE())) AS DT) AS A
              FROM [Sheet1$]'

由于

1 个答案:

答案 0 :(得分:1)

您需要添加双引号:

INSERT INTO OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
                       'Excel 8.0;Database=C:\testing.xls;', 
       'DECLARE @VPTVARCHAR(24) SET @VPT= ''Philips''
        DECLARE @DAYS INT SET @DAYS = -30   

        SELECT * 
        INTO #XTP1 
        FROM (SELECT DISTINCT ''START'' AS DTT, DATEADD(D,@DAYS,DATEACTIONED) AS DT 
              FROM REPORTS
              WHERE VPT = @VPT          
              UNION             
              SELECT DISTINCT ''CHANGE'' AS DTT, DATEACTIONED AS DT  
              FROM REPORTS
              WHERE VPT = @VPT          
              UNION             
              SELECT ''END'' AS DTT, DATEADD(dd, -1, DATEDIFF(dd, 0, GETDATE())) AS DT) AS A
              FROM [Sheet1$]')

这将消除语法错误,而不是查看查询