Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

dynamic field name

Posted on 2002-03-17
5
Medium Priority
?
223 Views
Last Modified: 2008-02-20
hi experts,

i heve the following code:

declare cursor_me cursor for select a_fielname from a_table
open cursor_me
fetch next from cursor_me into @my_var1

is there a way that based of some logic, it will tell me which field in the table that i should select?

i try to do the following but it did not give me the correct value

declare cursor_me cursor for select @my_var2 a_table
open cursor_me
fetch next from cursor_me into @my_var1

please help me out. thanks in advance!

0
Comment
Question by:megatshamsul
  • 2
5 Comments
 
LVL 143

Expert Comment

by:Guy Hengel [angelIII / a3]
ID: 6876283
unless you can avoid the cursor, you must put everything into dynamic SQL...

CHeers
0
 

Author Comment

by:megatshamsul
ID: 6878814
how?

some example may be.. thanks!
0
 
LVL 143

Accepted Solution

by:
Guy Hengel [angelIII / a3] earned 200 total points
ID: 6879334
cursor in dynamic SQL:

declare @sql nvarchar(1000)
declare @myvar varchar(100)

set @sql = N'declare cursor_me cursor for select cast(' + @my_var2 + 'as varchar(100)) from a_table
open cursor_me
fetch next from cursor_me into @my_var1
close cursor_me
deallocate cursor_me'

exec sp_executesql @sql, N'@my_var1 varchar(100) OUTPUT', @myvar OUTPUT

select @myvar

Cheers
0
 

Expert Comment

by:CleanupPing
ID: 9280760
megatshamsul:
This old question needs to be finalized -- accept an answer, split points, or get a refund.  For information on your options, please click here-> http:/help/closing.jsp#1 
EXPERTS:
Post your closing recommendations!  No comment means you don't care.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
In the first part of this tutorial we will cover the prerequisites for installing SQL Server vNext on Linux.
Via a live example, show how to backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.
Via a live example, show how to shrink a transaction log file down to a reasonable size.

971 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question