Friday, February 17, 2012

Dynamic SQL question

Can someone tell me why the exec statement throws the following error?
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '-'.

Code Snippet

create table #t (Val1 smallint, Val2 smallint )
go
DECLARE @.Diff as int;
set nocount on

insert into #t values(10, 15)

--Why does this work?
SET @.Diff=(SELECT Val2 FROM #t) - (SELECT Val1 FROM #t)
select @.Diff

--And yet this does not?
EXEC('(SELECT Val2 FROM #t) - (SELECT Val1 FROM #t)')

drop table #t
go


Thanks

Colin

It is because you dont have a SELECT or anything in your dynamic sql.

change to:

Code Snippet

EXEC('SELECT (SELECT Val2 FROM #t) - (SELECT Val1 FROM #t)')

and it works fine.

No comments:

Post a Comment