How do I execute a variable that contains a query string?

  • Hi there,

    Given the following….

    declare @qrystr varchar(4000)

    set @qrystr = 'select * from table1'

    How do I execute the actual query?

    Thank you very much.

  • You can either use exec(@qrystr) or use sp_executesql. Tend towards sp_executesql, since it at least slightly reduces the dangers of dynamic SQL (which is what this is).

    - Gus "GSquared", RSVP, OODA, MAP, NMVP, FAQ, SAT, SQL, DNA, RNA, UOI, IOU, AM, PM, AD, BC, BCE, USA, UN, CF, ROFL, LOL, ETC
    Property of The Thread

    "Nobody knows the age of the human race, but everyone agrees it's old enough to know better." - Anon

  • Thank you.

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply