Debug SQL Easily by Charles Carroll

来源:互联网 发布:cf审判无影腿编程 编辑:程序博客网 时间:2024/04/29 20:20

This page demonstrates how you can format a SQL statement to help pinpoint common errors. Common errors are discussed @

Common SQL Errors
http://www.learnasp.com/learn/dbtroubleshoot2.asp

Syntax Error in SQL Statement
http://www.learnasp.com/learn/FAQdbSQLSyntax.asp

by encapsulating ADO error trapping and display the SQL in an attractive form that separates components onto separate lines and makes debugging simpler (missing commas, single-quotes and like).

<Test Script Below>

<html><head>
<title>debug2.asp</title>
</head><body bgcolor="#FFFFFF">
<%
on   error resume next
myDSN = "DSN=Student;uid=student;pwd=magic"
Set Conn = Server.CreateObject("ADODB.Connection")
conn.open myDSN

SQL="update test set fname='Ted',lname='Wilson',city='Rockville',state='MD',zip='20849',rank=7,datehire='1/15/92', SSN='219-92-2677' WHERE personid=7"
Conn.Execute SQL,howmany
IF  howmany="" THEN
   howmany=0
END IF
response.write "Affected <b>" & howmany & "</b> records<br>"
Call SQLerrorreport(SQL,conn)

SQL="Insert Into junk (fname,lname,city,state,zip,rank,datehire,ssn) VALUES ('ted','wilson','rockville', 'md', '20849',7,'1/15/92','219-92-2677')"
Conn.Execute SQL,howmany
IF  howmany="" THEN
   howmany=0
END IF
response.write "Affected <b>" & howmany & "</b> records</b><br>"
Call SQLerrorreport(SQL,conn)

Conn.Close
set conn=nothing
%>

</body></html>
<!--#include file="lib_debug2.asp"-->

The library that does the work:

<%
SUB SQLErrorReport(parmSQL,parm_conn)
   HowManyErrs=parm_conn.errors.count
   IF HowManyErrs=0 then
      exit sub
   END IF
   pad="&nbsp;&nbsp;&nbsp;&nbsp;"
   lb="<br>" & vbcrlf
   comma="<font color=red>"
   squote="<font color=blue>"
   response.write "ADO Error(s) executing:<br>"
   for counter= 0 to HowManyErrs-1
      errornum=parm_conn.errors(counter).number
      errordesc=parm_conn.errors(counter).description
      response.write pad & "Error#=<b>" & errornum & "</b><br>"
      response.write pad & "Error description=<b>"
      response.write errordesc & "</b><p>"
   next
   SQLstmt=parmSQL
   SQLstmt=replace(SQLstmt,",", "<b>" & comma & ",</b></font>" & lb)
   SQLstmt=replace(SQLstmt,"'","<b>" & squote & "'</b></font>")
   SQLstmt=replace(SQLstmt,"(",lb & "(")
   SQLstmt=replace(SQLstmt,"set",lb & "set" & lb)
   SQLstmt=replace(SQLstmt,"SET",lb & "SET" & lb )
   SQLstmt=replace(SQLstmt," where ",lb & " where " & lb)
   SQLstmt=replace(SQLstmt," WHERE ",lb & " WHERE " & lb )
   
   SQLstmt=replace(SQLstmt,")",")" & lb)
         response.write "SQL statement attempted:<br>"
         response.write SQLstmt & "<br>"

END SUB
%>

原创粉丝点击