Parametrizing TOP value in tsql and pyodbc

前端 未结 2 965
醉话见心
醉话见心 2021-01-23 19:31

I try to parametrize number of top rows to get from table.

I tried it with

db.cursor.execute(
        \'\'\'
        SELECT TOP ? VALUE FROM mytable 
           


        
相关标签:
2条回答
  • 2021-01-23 20:10

    You can use string formatting for the TOP (and a proper parameter for the WHERE) provided that top_limit is an int so there is very little danger of SQL Injection issues.

    0 讨论(0)
  • 2021-01-23 20:27

    You can parameterize top by surrounding the value with parenthesis:

    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;
    

    Applied to the code you've posted:

    SELECT TOP (?) VALUE 
    FROM mytable 
    WHERE param = ? 
    
    0 讨论(0)
提交回复
热议问题