python-在tsql和pyodbc中参数化TOP值

我尝试参数化从表中获取的最上面几行.

我尝试过

db.cursor.execute(
        '''
        SELECT TOP ? VALUE FROM mytable 
        WHERE param = ? 
        ''',
        top_value, param
    )

它显示

pyodbc.ProgrammingError: (‘42000’, “[42000] [Microsoft][ODBC Driver 17
for SQL Server][SQL Server]Incorrect syntax near ‘@P1’. (102)
(SQLExecDirectW)”)

像波纹管这样的字符串插值可以工作.

    db.cursor.execute(
        f'''
        SELECT TOP {top_limit} VALUE FROM mytable 
        WHERE SITE_SK_FK = ? 
        ''',
        param
    )

我需要将其作为参数传递,还是字符串插值足够好?

解决方法:

您可以通过用括号将值括起来来对top进行参数化:

DECLARE @Top int = 5;

With Tally(N) AS
(
    SELECT ROW_NUMBER() OVER(ORDER BY @@SPID)
    FROM sys.objects
)

-- This works just fine
SELECT TOP (@Top) N
FROM Tally;

-- This will raise an error: Incorrect syntax near '@Top'
SELECT TOP @Top N 
FROM Tally;

应用于您发布的代码:

SELECT TOP (?) VALUE 
FROM mytable 
WHERE param = ? 
上一篇:使用odbc_connect从SQLAlchemy连接到SQL Server


下一篇:python-用pyodbc加入mdb表