[Tutor] Multi-Line SQL Statement in Python

Gooch, John John.Gooch at echostar.com
Sat Nov 20 00:47:39 CET 2004


I have a rather involved query to run on an MS SQL Server 2000 system. I
developed the query using the MS SQL Query Analyzer, and it returns 5
records when I run it from there. I attempted to simply copy/paste it into a
multi-line Python string ( full query below ), but the query fails when
calling the odbc.cursor.fetchall()|odbc.cursor.fetchone() function within
Python. First thing I tried to do to solve this issue was to add a newline
character after every statement, in case it was running all of the commands
together. That did not help. Secondly, I added backslashes before potential
special characters ( I only identified '%' as special ) within the script.
Still doesn't work. 

Am I missing any other formatting options/ special characters that could be
tripping up my query? Perhaps the single quotes  also need to be escaped?  I
am at quite a loss. While I would love to store the query server side, that
database is part of a proprietary software application, and I cannot safely
make any modifications to its structure without the risk of trashing the
system or violating licensing restrictions. 


Any help would be appreciated. 


    ssql = """--Get the Server's Object ID"  
            DECLARE @ServerID int   
            SELECT
                @ServerID = ob.objid
            FROM 
                dbo.object as ob
            WHERE 
                ob.name = 'SUPERMAN'
        
            --Find Out How Many Drives it Has
            DECLARE @intCount int
            SELECT 
                     @intCount = COUNT(*)
            FROM 
                    dbo.ArchiveDataHeader As adh (NOLOCK) 
            WHERE 
                            adh.MCMachineObjID=@ServerID	
                    AND
                            adh.Legend LIKE 'Ldsk: \%AVAIL^^MB'		
            DECLARE @exec varchar(256)

            SET ROWCOUNT @intCount
            --Get the latest Drive Space Records
            SELECT adh.Legend,ad.DetailShort
            FROM 
                    dbo.ArchiveDataHeader As adh (NOLOCK), dbo.ArchiveData
As ad (NOLOCK)
            WHERE
                            adh.MCMachineObjID=@ServerID
                    AND
                            ad.DataID=adh.DataID
                    AND
                            adh.Legend LIKE 'Ldsk: \%AVAIL^^MB'	
                    AND
                            DATEDIFF( day, DATEADD( second, ad.BiasedTime,
'19700101' ), getdate() ) < 2 
            ORDER BY
                    DATEADD( second, ad.BiasedTime, '19700101' ) DESC
           """

John A. Gooch
Systems Administrator
IT - Tools
EchoStar Satellite L.L.C.
9601 S. Meridian Blvd.
Englewood, CO  80112
Desk: 720-514-5708 


More information about the Tutor mailing list