Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
kgundava
Yak Posting Veteran
66 Posts |
Posted - 2011-08-02 : 10:59:58
|
| Hi All, I have to generate a where clause dynamically using a cursor.It would be helpful for me if you could let me know how can i concatenate a Varchar variable i.e @WHERECLAUSE with a string generated.Please see below... OPEN @WHERCLAUSE_CURFETCH NEXT FROM @WHERCLAUSE_CUR INTO @COLUMN_NAMWHILE @@FETCH_STATUS = 0BEGIN@WHERECLAUSE + 'S.'+@COLUMN_NAM+'=T.'+@COLUMN_NAM+''FETCH NEXTFROM @WHERCLAUSE_CUR INTO @COLUMN_NAMEND Thanks...... |
|
|
michael.appleton
Posting Yak Master
160 Posts |
Posted - 2011-08-02 : 11:30:09
|
Cursors and dynamic SQL! Are you trying to wind to some people up here? Wait unitl Celko sees this...Hehe!Seriously, this is probably not a good approach. You've asked how to concatenate a varchar variable, but you've done it in your example using the "+" operator sort of... If you want to save the results into the variable @WHERECLAUSE use:SET @WHERECLAUSE=@WHERECLAUSE + 'S.'+@COLUMN_NAM+'=T.'+@COLUMN_NAM+' AND ' --Guessing you'll need to link up the different conditions somehow But yeah, like I said, dynamic sql and cursors, usually a bad idea! |
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2011-08-02 : 11:48:56
|
| why is your column varying? cant you determine columns before execution time?------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/ |
 |
|
|
Transact Charlie
Master Smack Fu Yak Hacker
3451 Posts |
Posted - 2011-08-02 : 12:09:25
|
What visakh said -- this is probably a bad, bad plan.However, here is some magic.SET NOCOUNT ONDECLARE @testTable TABLE ([val] VARCHAR(10))INSERT @testTable ([val]) SELECT 'a'UNION SELECT 'b'UNION SELECT 'c'UNION SELECT 'd'-- Start magic hereDECLARE @abracadabra VARCHAR(MAX) SET @abracadabra = ''SELECT @abracadabra = @abracadabra + [val] + CHAR(13) + CHAR(10)FROM @testTableORDER BY [val] ASC-- End MagicPRINT @abracadabra Results:abcd You can concatenate strings just using SELECT - which will outperform a cursor by several hundred times. However, you probably shouldn't be doing what you are suggesting to do.Charlie===============================================================Msg 3903, Level 16, State 1, Line 1736The ROLLBACK TRANSACTION request has no corresponding BEGIN TRANSACTION |
 |
|
|
kgundava
Yak Posting Veteran
66 Posts |
Posted - 2011-08-02 : 13:55:31
|
| Thanks for the responses.I would be trying your approaches and let you guys know the result. |
 |
|
|
|
|
|
|
|