Home > Archive > MS SQL Server MSEQ > August 2005 > EXEC (select... ) problem Help!









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author EXEC (select... ) problem Help!
Scagnetti

2005-08-06, 11:23 am

How can I get this to work?
declare @WkEmpID
declare @sql varchar(1000)

set @sql = 'select distinct @WkEmpID = EmpID from Employee'
exec (@sql)

Now this is a simplified version of a more comples query which is forcing me
to use this method rather than a simple SQL query. The big problem is getting
the 'EmpID' value into the local variable of '@WkEmpID'. Please help!
Hugo Kornelis

2005-08-06, 1:23 pm

On Sat, 6 Aug 2005 08:20:03 -0700, Scagnetti wrote:

>How can I get this to work?
>declare @WkEmpID
>declare @sql varchar(1000)
>
>set @sql = 'select distinct @WkEmpID = EmpID from Employee'
>exec (@sql)
>
>Now this is a simplified version of a more comples query which is forcing me
>to use this method rather than a simple SQL query. The big problem is getting
>the 'EmpID' value into the local variable of '@WkEmpID'. Please help!


Hi Scagnetti,

First: do try to solve this without dynamic SQL. There are often other
ways to get the same result. Consider posting your real problem here;
maybe someone sees a solution you didn't think of. For a discussion and
the pro's and (mainly) con's of dynamic SQL, visit Erland Sommarskog's
site: http://www.sommarskog.se/dynamic_sql.html.

The answer to your question is to use the stored procedure sp_executesql
instead of exec (@sql). Details in Books Online (and on Erland's page).
But as I said - doing it without dynamic SQL is the best solution.

Best, Hugo
--

(Remove _NO_ and _SPAM_ to get my e-mail address)
Dandy Weyn [Dandyman]

2005-08-09, 3:24 am

Here's an example on how to build a dynamic SQL string and run it with
EXECUTE or SP_EXECUTESQL stored procedure

http://www.dandyman.net/sql/samples/dynamicsql.txt


--
Dandy Weyn
[MCSE-MCSA-MCDBA-MCDST-MCT]
http://www.dandyman.net

Check my SQL Server Resource Pages at http://www.dandyman.net/sql
"Scagnetti" < Scagnetti@discussion
s.microsoft.com> wrote in message
news:7363AFA0-2098-4014-9BEB- FFF6F5D697DC@microso
ft.com...
> How can I get this to work?
> declare @WkEmpID
> declare @sql varchar(1000)
>
> set @sql = 'select distinct @WkEmpID = EmpID from Employee'
> exec (@sql)
>
> Now this is a simplified version of a more comples query which is forcing
> me
> to use this method rather than a simple SQL query. The big problem is
> getting
> the 'EmpID' value into the local variable of '@WkEmpID'. Please help!



Sponsored Links





Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive | Programming forum archive

Copyright 2008 droptable.com