Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Set selected value to a variable
Message
 
General information
Forum:
Microsoft SQL Server
Category:
Other
Environment versions
SQL Server:
SQL Server 2005
Miscellaneous
Thread ID:
01544218
Message ID:
01544233
Views:
38
This message has been marked as the solution to the initial question of the thread.
>>>Hi,
>>>
>>>The only way I found that I can assign a value selected in SQL Select to a variable as following:
>>>
>>>
>>>select @MyVar = (select MyColumn1 from MyTable where MyColumn2 = 'SomeValue')
>>>
>>>
>>>Is the above the only way to do it? Or there is a better approach? TIA.
>>
>>Another way is
>>
>>select @MyVar = MyColumn1 from myTable
>>
>>The difference between these two methods is that the first will always change the @MyVar variable. In the second case, if the select statement does not produce rows, the original value of @MyVar will not change.
>
>
>Can you think of why the following SLQ Select (selecting from an XML string):
>
>
>SELECT @Var1 = [Fld FldName].value('.','varchar(20)'),  [Fld FldName].value('@Name','varchar(20)') AS FldName
>  FROM @myxml.nodes('/TABLENAME/Fld') Fld([Fld FldName]) where [Fld FldName].value('@Name','varchar(20)')='Field1'
>
>
>gives error:
>
>A SELECT statement that assigns a value to a variable must not be combined with data-retrieval operations.
>
You can not mix assigning the variables and selecting a column in the same statement. It should be
SELECT @Var1 = [Fld FldName].value('.','varchar(20)'),  @Var2 = [Fld FldName].value('@Name','varchar(20)')
  FROM @myxml.nodes('/TABLENAME/Fld') Fld([Fld FldName]) where [Fld FldName].value('@Name','varchar(20)')='Field1'
If it's not broken, fix it until it is.


My Blog
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform