0

Why if in SQL Server, I have a column defined as XML type, and in .NET with SqlDataReader/SqlDataAdapter I have a string?

See the example in the screenhsot, cast c1 in XML, but .NET gets a string.

I tried also with XML column, always string.

See the example in pic, cast value in xml, but .Net get string.

This my code

SqlCommand sc = new SqlCommand("select *, convert(xml, c1) c6 from tempdb..t1", conn);

DataTable dt = new DataTable();
new SqlDataAdapter(sc).Fill(dt);

How can I recognize a XML result to cast only when necessary?

4
  • 2
    That's how it reads it. You can use GetSqlXml if you have a reader learn.microsoft.com/en-us/dotnet/api/… but otherwise it will just turn it into a string. Commented Jul 9, 2024 at 13:07
  • how can i recognize a xml result? Commented Jul 9, 2024 at 13:09
  • 3
    reader.GetDataTypeName tells you the type. By the way your code in the screenshot rather ominously uses both SqlDataAdapter` and SqlDataReader which means you are probably executing the command twice. You are also missing using to dispose everything. Commented Jul 9, 2024 at 14:23
  • @Charlieface: perfetct, this was i needed! Commented Jul 9, 2024 at 20:09

1 Answer 1

0

SOLUTION

as suggested by @Charlieface, instead of

dr[n].GetType() // get System.String (.net type)

i used

dr.GetDataTypeName(n) // get xml (sql type)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.