使用Dynamic T-SQL INSERT INTO OPENROWSET语法

时间:2014-09-09 20:44:46

标签: sql-server tsql

我觉得我已经在线阅读了有关如何从T-SQL脚本动态创建Excel输出的每一页。这就是我所拥有的:

Use Master
GO

EXEC master.dbo.sp_configure 'show advanced options', 1
RECONFIGURE WITH OVERRIDE
GO

EXEC master.dbo.sp_configure 'xp_cmdshell', 1
RECONFIGURE WITH OVERRIDE
GO

EXEC sp_configure 'ad hoc distributed queries', 1
RECONFIGURE
GO

EXEC master . dbo. sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0' , N'AllowInProcess' , 1
GO

EXEC master . dbo. sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0' , N'DynamicParameters' , 1
GO

USE CommercialLending
GO
DECLARE @LoopCounter TINYINT = 1
DECLARE @LoopMaxCount TINYINT = (SELECT COUNT(DISTINCT OFFICER)
                                FROM CommercialLending.dbo.CMLTrial)
WHILE (1=1)
BEGIN
DECLARE @OfficerName VARCHAR(4000) = (
                                    SELECT OFFICER 
                                    FROM (SELECT DISTINCT OFFICER, ROW_NUMBER() OVER (ORDER BY OFFICER) AS rownumber 
                                            FROM CommercialLending.dbo.CMLTrial GROUP BY Officer) AS OFFICER 
                                    WHERE rownumber = @LoopCounter)
DECLARE @FileName varchar(400) = @OfficerName+ '.xlsx'
DECLARE @FullFileName varchar(400) = 'O:\MIS\Python\Programs\CommercialLending\'+@FileName
DECLARE @CopyFile varchar(800) = 'copy O:\MIS\Python\Programs\CommercialLending\Template.xlsx copy O:\MIS\Python\Programs\CommercialLending\' + @FileName
EXEC xp_cmdshell @CopyFile
DECLARE @sql nvarchar(4000)
SET @sql = 'INSERT INTO OPENROWSET(''Microsoft.ACE.OLEDB.12.0'',Excel 12.0;Database='+@FullFileName+';'',''SELECT * FROM [Sheet1$])'' SELECT * FROM dbo.CMLTrial WHERE Officer='''+@OfficerName+''
EXEC (@sql)
SET @LoopCounter = @LoopCounter+1
IF (@LoopCounter > @LoopMaxCount)
    BREAK;
END

Use Master
GO

EXEC master.dbo.sp_configure 'xp_cmdshell', 0
RECONFIGURE WITH OVERRIDE
GO

EXEC sp_configure 'ad hoc distributed queries', 0
RECONFIGURE
GO

EXEC master.dbo.sp_configure 'show advanced options', 0
RECONFIGURE WITH OVERRIDE
GO

EXEC master . dbo. sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0' , N'AllowInProcess' , 0
GO

EXEC master . dbo. sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0' , N'DynamicParameters' , 0
GO

我知道我的问题在于将INSERT INTO OPENROWSET字符串分配给@sql变量:

SET @sql = 'INSERT INTO OPENROWSET(''Microsoft.ACE.OLEDB.12.0'',Excel 12.0;Database='+@FullFileName+';'',''SELECT * FROM [Sheet1$])'' SELECT * FROM dbo.CMLTrial WHERE Officer='''+@OfficerName+''

对于我的生活,我无法弄清楚我的语法错误在哪里。有人可以帮我解决这个问题,并且如果可能的话,还可以提供一个指南来确定使用INSERT INTO OPENROWSET作为变量中字符串的标准语法吗?

1 个答案:

答案 0 :(得分:4)

试试这个:

    SET @sql = 'INSERT INTO OPENROWSET(''Microsoft.ACE.OLEDB.12.0'',''Excel 12.0;Database='+@FullFileName+''',''SELECT * FROM [Sheet1$]'') SELECT * FROM dbo.CMLTrial WHERE Officer LIKE '''+@OfficerName+''''

在处理动态脚本时,我总是使用PRINT @sql来查看实际查询的外观。它可以更容易地排除故障,并在以后为我节省大量的悲伤。