Pass parameters to temp variables in MS Query on SQL Server from Excel

為{幸葍}努か 提交于 2019-12-10 21:22:42

问题


I have created a parameter query using Microsoft query as mentioned here. But when I want to pass parameters to temporary variables and create table variables and edit them to get the desired result instead of doing 10 to 15 Joins and mentioning the parameters in the where clause I get errors

[Microsoft] [ODBC SQL Server Driver] Invalid Parameter number

and

[Microsoft] [ODBC SQL Server Driver] Invalid Descriptor Index

My code looks something like this it is way complex with many temp tables and temp variables

BEGIN
    SET NOCOUNT ON

    DECLARE @sDate DATETIME, @eDate DATETIME; --used in many places to manipulate temp table

    SET @sdate = ?
    SET @edate = ?

    DECLARE @Temptable TABLE (Variable1 INT ,...... VariableN DECIMAL(18,4));

    Manipulate @temptable

    Select * from @Temptable 
END 

How is it possible to pass parameters to temp variables in Excel 2007 for a database in SQL Server 2005? I have no permission to create stored procedures in the database and pass them as parameters to it.

UPDATE

I have figured a way through VBA as suggested by David Vandenbos. I am still curious to know if this can be done without the help of VBA.


回答1:


You can add SET NOCOUNT ON before declaring the variables. I works perfectly in Excel 2010 with Microsoft Query and SQL Server 2005.

SET NOCOUNT ON
DECLARE @VAR1 VARCHAR(4)
SET @VAR1 = '1234'
SELECT @VAR1

https://social.msdn.microsoft.com/Forums/office/en-US/d8003854-d11a-44f7-960c-a042347736d7/microsoft-query-cannot-run-sql-code-with-a-tsql-variables-in-it?forum=exceldev



来源:https://stackoverflow.com/questions/15848015/pass-parameters-to-temp-variables-in-ms-query-on-sql-server-from-excel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!