Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Dynamic SQL Question

Status
Not open for further replies.

ccscott

Programmer
Mar 13, 2006
14
US
Total newbie question, but i'm having some trouble executing the following dynamic sql statement. The folowing represents an example of the piece of code...

CREATE TABLE #Temp([VID] INT)
INSERT INTO #Temp VALUES(6565)
ALTER TABLE #Temp ADD Counter INT

DECLARE @SQL VARCHAR(250)
DECLARE @VID INT
DECLARE @COUNTERVAR INT

SET @VID='6585'
SET @COUNTERVAR=1

SET @SQL = 'UPDATE #Temp SET COUNTER = '+ @COUNTERVAR +' WHERE VID='+ @VID + ''
EXEC (@SQL)


Below is the error message that I am receiving

Conversion failed when converting the varchar value 'UPDATE #Temp SET COUNTER = ' to data type int.
 
You don't need dynamic sql in this case. The following will run fine:

Code:
CREATE TABLE #Temp([VID] INT)
INSERT INTO #Temp VALUES(6565)
ALTER TABLE #Temp ADD Counter INT

DECLARE @SQL VARCHAR(250)
DECLARE @VID INT
DECLARE @COUNTERVAR INT

SET @VID='6585'
SET @COUNTERVAR=1

UPDATE #Temp SET COUNTER =  @COUNTERVAR  WHERE VID = @VID
 
RiverGuy - Thanks; however i was just using this as an example for the sake of simplicity. I'm getting the same error when attempting to execute dynamic sql in a much larget block of code.
 
Man i wish i had that color coder...

You have do 2 ' inside the string in order to get 1, you were close.

A trick when working with dynamic SQL is to Print it, then exec the printed results to see the REAL error

Code:
CREATE TABLE #Temp([VID] INT)
INSERT INTO #Temp VALUES(6565)
ALTER TABLE #Temp ADD Counter INT

DECLARE @SQL VARCHAR(250)
DECLARE @VID INT
DECLARE @COUNTERVAR INT

SET @VID='6585'
SET @COUNTERVAR=1

SET @SQL = [red]'UPDATE #Temp SET COUNTER = '[/red]+ @COUNTERVAR +[red]' WHERE VID='''[/red]+ @VID + [red]'''[/red]
PRINT @SQL
EXEC (@SQL)

If [blue]you have problems[/blue], I want [green]source code[/green] AND [green]error messages[/green], none of this [red]"there was an error crap"[/red]
 
You need to cast your INTs to a string datatype. Try the following:

Code:
CREATE TABLE #Temp([VID] INT)
INSERT INTO #Temp ([VID]) VALUES(6565)
ALTER TABLE #Temp ADD Counter INT

DECLARE @SQL VARCHAR(250)
DECLARE @VID INT
DECLARE @COUNTERVAR INT

SET @VID='6565'
SET @COUNTERVAR=1

SET @SQL = 'UPDATE #Temp SET COUNTER = '+ CONVERT(VARCHAR(4), @COUNTERVAR) +' WHERE VID='+ CONVERT(VARCHAR(4), @VID) + ''
PRINT @SQL
EXEC (@SQL)
SELECT * FROM #Temp
DROP TABLE #Temp
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top