troubleshooting Question

Dynamic SQL Error

Avatar of ScuzzyJo
ScuzzyJoFlag for United Kingdom of Great Britain and Northern Ireland asked on
Microsoft SQL Server
4 Comments2 Solutions144 ViewsLast Modified:

I'm pretty new to using dynamic SQL and have the following bit of code:

SET @maxcounter = 0;
WHILE @maxcounter < @maxcnt
      SET @crtcnt = @maxcounter + 1;
      SET @maxcounter = @maxcounter + 1;
      SET @sqlstr = 'UPDATE LFRD SET  old_ssn' + @crtcnt + ' = substring(ConcatF,13*' + @maxcounter + ',13) WHERE old_ssn Is Not Null OR @maxcounter < SSNCount;'
      EXEC (@sqlstr);

The variables are declared and used earlier, so I'm pretty sure that isn't the problem.

I'm getting the error message:

Msg 245, Level 16, State 1, Line 137
Conversion failed when converting the nvarchar value 'UPDATE LFRD SET  old_ssn1 = substring(ConcatF,13*' to data type int.

Which refers to the @sqlstr =  line.

I'm pretty sure it's my syntax, but I don't understand why it's trying to convert to a data type int.

The line is supposed to fill various columns (the number is dynamic) with data from a concatenated column.  Each block of data is 13 characters long.  I'm trying to say that if @maxcounter is 1, start at character 13 (probably needs to be 14, but I can deal with that later) and pick up 13 characters.  If @maxcounter is 2, start at character 26 (or maybe 27) and pick up 13 characters, and so on.

Can anybody please help me here?  I don't know where I'm going wrong.

Join our community to see this answer!
Unlock 2 Answers and 4 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 2 Answers and 4 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros