Click here to Skip to main content
15,900,461 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,
I got a issue in query() method of xquery when i am trying to solve the arithmetic expression .
the problem is that
when i use the sql statments like this

DECLARE @x xml=''
DECLARE @x1 xml;
DECLARE @Result DECIMAL(38,8)
SET @x1= @x.query('1*12')
SET @Result= CAST(@x1.value('(/.)[1]', 'Float') AS DECIMAL(38,8))
Select @Result

then it returns the value 12.00000000 which is correct

but when i am going to use any variable in place of arithmetic expression like this


DECLARE @x xml=''
DECLARE @x1 xml;
DECLARE @Result DECIMAL(38,8)
DECLARE @r varchar(60)='1*12'
SET @x1= @x.query(@r)

SET @Result= CAST(@x1.value('(/.)[1]', 'Float') AS DECIMAL(38,8))
Select @Result

then it gives the error
The argument 1 of the XML data type method "query" must be a string literal.
i also tried
SET @x1= @x.query('sql:variable("@r")')

but it only gives only 1*12 not the value.

Please help me .
Posted
Comments
[no name] 31-Dec-14 6:36am    
Have you tried declaring the variable in the first line and then assigning the variable with the value "1*12"?

Try the following:
DECLARE @r varchar(60)
SET @r = '1*12'

I hope this will work.
vineet1304 31-Dec-14 6:49am    
i tried it but it also not worked and got the same error.

1 solution

Microsoft's help page clearly states (and the error also tells you) that query() can not get it's parameter from variable! It must have a string literal...
http://msdn.microsoft.com/en-us/library/ms191474.aspx[^]
You may try to create a dynamic query here...
 
Share this answer
 
Comments
vineet1304 31-Dec-14 7:49am    
but i can't execute the dynamic query within a function ,actually i am supposing to create a function in which i will pass the expression as argument which i have declare now as @r.
Kornfeld Eliyahu Peter 31-Dec-14 9:16am    
Check this - http://msdn.microsoft.com/en-us/library/ms188001.aspx
It can give you a solution how to run the query...
vineet1304 31-Dec-14 10:29am    
it doesn't provide any detail how to run sp_excutesql in user defined function
as i know we can't run the sp_excutesqlin the function.
Kornfeld Eliyahu Peter 31-Dec-14 11:38am    
You can't. But you have no other way to give query() it's parameter from variable...So you have to give up on one of them dynamic query() or UDF - can't have both...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900