I'm testing out a sql query on a query analyzer and it works just fine, here it is:
INSERT INTO Questions(QuestionText, QuestionType)
VALUES('test','test')
DECLARE @testID int
SET @testID = @@identity
INSERT INTO Questions(QuestionText)
VALUES (@testID)
(I'm just testing out the @@identity function)
However as soon as I try and implement it on my site (i'm using SQL in conjunction with asp Classic) I get an error, can someone tell me what i'm doing wrong please? Here is what I have put in the asp:
set rs=Server.CreateObject("ADODB.recordset")
rs.Open "Select * from Questions", conn
sql="INSERT INTO Questions(QuestionText, QuestionType)"
sql=sql & " VALUES "
sql=sql & "('" & qtext & "',"
sql=sql & "'" & "checkbox" & "')"
sql=sql & "DECLARE @testID int"
sql=sql & "SET @testID = @@identity"
sql=sql & "INSERT INTO Questions(QuestionText)"
sql=sql & " VALUES "
sql=sql & "(@testID)"
on error resume next
conn.Execute sql,recaffected
if err<>0 then
Response.Write("An Error Has Occured")
else
Response.write("Data Added")
end if
conn.close
Here are 2 simple and ready to use functions in classic ASP to execute SQL stuff
You have no spaces in your SQL when you are concatenating it, so this:
Is going to yield
As you can see you end up with invalid syntax here:
A quick fix would be to add spaces and/or terminate your statements properly with a semi-colon:
Better still would be to use parameterised queries as well, your current code is not type safe, vulnerable to sql injection, and cannot take advantage of query plan caching.
Finally
@@IDENTITY
is almost never the correct function to use, you should be using SCOPE_IDENTITY() for this - See this answer for more infoEDIT
I know this is only a proto type query for testing, but you could transform your query into a single statement as follows:
The first output statement will insert the value of QuestionText you are inserting into the table again, the second output will return this value to ASP.