Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select Test As [text()]

Tags:

t-sql

I have inherited this line of code. Normally, I would expect what occurs after the As to be an alias. However, I have never seen an alias in square brackets. Also, I'm not sure what the parens in text() signify? Is text an obsolete data type? Is there any link someone can send me so I can figure out what this means?

Thank you.

like image 323
Keith Howard Avatar asked Feb 22 '26 21:02

Keith Howard


2 Answers

The [text()] alias is often used in XML queries to make the value from a column become the text output in an element:

DECLARE @Table TABLE (FieldText varchar(10))
INSERT INTO @Table VALUES ('some text'), ('more text')

SELECT FieldText
FROM @Table 
FOR XML PATH('RECORD'), ROOT('ROOT'), TYPE

--<ROOT>
--  <RECORD>
--    <FieldText>some text</FieldText>
--  </RECORD>
--  <RECORD>
--    <FieldText>more text</FieldText>
--  </RECORD>
--</ROOT>

SELECT FieldText as [text()]
FROM @Table 
FOR XML PATH('RECORD'), ROOT('ROOT'), TYPE

--<ROOT>
--  <RECORD>some text</RECORD>
--  <RECORD>more text</RECORD>
--</ROOT>
like image 89
J Bryan Price Avatar answered Feb 27 '26 03:02

J Bryan Price


However, I have never seen an alias in square brackets

It can be, if you are trying to use a keyword/reserveword as your alias name (OR) if you are trying to use a name which has spaces between them like My Special Alias name

Using As [text()] looks bit weird to me. No it doesn't signifies anything. Alias names are just text literal for better readable name but I would suggest use proper name which increases readability else there is no point in using alias name(s).

like image 32
Rahul Avatar answered Feb 27 '26 03:02

Rahul