Avatar of malraff
malraff
Flag for Ireland asked on

sql2005: attaching a variable to a field

hi all

trying to improve upon some sql code i may need, and if its possible i think being able to add a variable to afield may just be the answer

is this possible ? or am i just barking up the wrong tree?

eg
if @count < 54
@count +1
update field'@count'        - where my fields are week1,week2,week3,week4 etc etc


cheers

mal
Microsoft SQL ServerMicrosoft SQL Server 2005

Avatar of undefined
Last Comment
malraff

8/22/2022 - Mon
stalhw

It is...
You can build an query as a string and then execute it...
like:
declare @string nvarchar(100),
  @count int

SET @count=11

SELECT @string=N'SELECT top '+convert(nvarchar,@count)+' * FROM someTable'
EXEC(@string)
or (if you have complex sql with variables) :
EXECUTE sp_executesql(@string)



for sp_executesql see http://msdn.microsoft.com/en-us/library/ms188001.aspx
malraff

ASKER
hi stalhw

sorry im a little slow - how do i apply that to an update like below

where basically i want to say

declare @variable int, @num int
@variable = @variable +1
@num = @num +7
update tableA set week@variable = dateadd(day,@num, (GETDATE()))
ASKER CERTIFIED SOLUTION
stalhw

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
stalhw

ops meant
exec(@string)
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
malraff

ASKER
ah yes :)

cheers for that, takes a while but usually sinks in !

will test and hopefully i can turn 53 lines of code into a few !
malraff

ASKER
cheers stalwh!