I have this SQL query that I am running on a .NET application, and I want to determine the types of each of the column of the resulting query. The query has multiple joins, column aliasing and possible casting as well. For example I could have something like this,
SELECT
T1.col1,
T1.col2,
T2.col1 AS alias1,
CAST(T2.col2 AS varchar) AS cast1,
CAST(T3.col1 AS nvarchar) AS cast2,
T3.col2 AS alias2
FROM table1 T1
LEFT JOIN table2 T2
ON T1.joincol = T2.joincol
INNER JOIN table3 T3
ON T2.joincol2 = T3.joincol
Currently, in my application, I am selecting a TOP 1 from this query and putting it into a DataTable object. From there, I determine the type by looking at the DataType property for each of the columns. However, I need to make the distinction between varchar and nvarchar.
I need to find a way to get the data types of the columns in the results of this query. For example, the data type of col1, col2, alias1, cast1, cast2, alias2. Is there a way to do this in the SQL query itself? I know there is sys.columns
, but it only has the information for the source table and I'm not sure how to handle the cases above where I am aliasing columns and casting.
Alternatively, is there a way to do this on the C# side? In both cases where I am selecting varchar and nvarchar types from SQL, it puts it into the DataTable as a System.String
. Is there some property in the DataType accessor that will indicate whether or not it is varchar or nvarchar? Or is there another way to determine this using the DataTable or something else?