简体   繁体   中英

Setting a variable in a SQL WHERE clause to be used in SELECT

I'm using Transact-SQL with Microsoft SQL Server, and we have a query that looks like this:

SELECT Cast( Cast ( Cast(XMLBlob as XML).query(N'//continent/forest/tree/age/Text()') as nvarchar) as bigint), 
AnotherField
FROM [MyDB].[dbo].[mytable]
WHERE Cast( Cast ( Cast(XMLBlob as XML).query(N'//continent/forest/tree/age/Text()') as nvarchar) as bigint) 
between 10 and 100 

The XML cast is an expensive operation, and since it's used in both the WHERE and SELECT, it seems like I should be able to save it away as a variable in the WHERE (which, by order of operations, is evaluated before the SELECT), and use it in the SELECT instead of having to cast again. Is this possible?

You could use an inner query where you retrieve the XML value. Then outside the inner query you both return that bigint value and filter the values you want:

SELECT innerTable.Age, innerTable.AnotherField
FROM (
    SELECT Cast( Cast ( Cast(XMLBlob as 
    XML).query(N'//continent/forest/tree/age/Text()') as nvarchar) as bigint) AS Age, 
    AnotherField
    FROM [MyDB].[dbo].[mytable]
) AS innerTable
WHERE innerTable.Age between 10 and 100 

By the way... why do you need a bigint to store Age? If you are storing years looks like overkill, even for those trees that live thousands of years :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM