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 SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Executing Dynamic SQL Statement 1

Status
Not open for further replies.

ninelgorb

Programmer
Mar 7, 2005
111
0
0
US
I have the following dynamic statement:

Code:
SET @sSQL =  'INSERT INTO ' + @Table + ' (sCalldate, sAgentid, sProject, sLogIn, sLogOut, sCallTime, dCallSec) ' + ' VALUES ( ''' +  @sCalldate + ''', ''' +  @cursorAgentId + ''', ''' +  rtrim(ltrim(@sProject)) + 'z' + ''', ''' +  @sStartTime + ''', ''' + @sEndTime  + ''', ''' + convert(char(8), convert(datetime, @sEndTime) - @sStartTime, 108)  + ''', ' + Convert(varchar(10),( datediff(ss, 0, convert(char(8), convert(datetime, @sEndTime) - @sStartTime, 108))) ) +  ')'

The actual statement looks like this:
Code:
INSERT INTO tmTaskTimeDetailsNonVoiceNet (sCalldate, sAgentid, sProject, sLogIn, sLogOut, sCallTime, dCallSec)  VALUES ( '20050714', '4358', 'jhtc0z', '10:00:00', '11:30:00', '01:30:00', 5400)

When I execute it manually the record gets inserted, but when I use EXEC @sSQL I get the following error:
"INSERT INTO tmTaskTimeDetailsNonVoiceNet (sCalldate, sAgentid, sProject, sLogIn, sLogOut, sCallTime, dCallSec) VALUES ('20050714', '4358', 'jhtc0z', '10:00:00', '11:30:00', '01:30:00', 5400)' is not a valid identifier."

What does this error mean? What am I doing wrong??

Thanks,
Ninel
 
Thank you so much. I love it when it's such a simple fix.
 
Can I select into a #TEMP table using dynamic sql?

For example:
Code:
SET @sSQL =  'SELECT * INTO #TEMP FROM ' + @sTable

EXEC (@sSQL)

I'm getting an invalid object name error when trying to select from #TEMP.

Thanks,
Ninel
 
You can create a temp table first, and then insert exec.

Ex.

Code:
Create Table #Temp(Field1 int, Field2 VarChar(20), etc..)

Insert Into #Temp
Exec (@sSQL)

You need to build the table structure for the #Temp table so that it matches the returned table structure of your dynamic SQL string.

-George

Strong and bitter words indicate a weak cause. - Fortune cookie wisdom
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top