1

I am trying to run my query on a SQL Server 2008 where the compatibility level doesn't support try_convert().

SELECT TOP 1
    A.PTNTIDNO,
    A.LR,
    CASE WHEN ISNULL(A.ITEM1, '') = ''
        THEN (select ROUND(AVG(TRY_CONVERT(float, ITEM1)),3) from INFLABD)
        ELSE TRY_CONVERT(float,A.ITEM1, 3)
    FROM INFLABD AS A
    WHERE A.LR = 'R'
    AND A.PTNTIDNO = %s
    ORDER BY A.REGDATE DESC

Error message

File "src\pymssql_pymssql.pyx", line 478, in pymssql._pymssql.Cursor.execute pymssql._pymssql.OperationalError: (195, b"'TRY_CONVERT' is not a recognized built-in function name.DB-Lib error message 20018

Therefore, is there another alternative?

Follow your comment

cast('' as xml).value('sql:column("A.RIGHT01") cast as xs:decimal ?', 'decimal(28,10)')

It worked well

but add aggregate function 'AVG'

THEN (select ROUND(AVG(cast('' as xml).value('sql:column("A.RIGHT01") cast as xs:decimal ?', 'decimal(28,10)')),3) from OPERATIONDATA)

Error message

Column 'OPERATIONDATA.RIGHT01' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.DB-Lib error message 20018

Add I solve the problem just change 'A.RIGHT01' to 'RIGHT01'

And now I'm curious about the query

THEN (select ROUND(AVG(cast('' as xml).value('sql:column("RIGHT01") cast as xs:decimal ?', 'decimal(28,10)')),3) from OPERATIONDATA)

Can explain this query..? I don't know why this is working well

  1. Is this only used as a alternative for when try_convert is not possible?
  2. I learned sql but this code is never seen before. So can explain?

cast('' as xml).value('sql:column("RIGHT01") cast as xs:decimal ?', 'decimal(28,10)'

Thank you for your support.

Tae In Kim
  • 194
  • 2
  • 13

1 Answers1

0

The problem is that A refers to the outer reference of INFLABD but you want to refer to the inner table. Effectively, what you need is sql:column("od.RIGHT01")

SELECT TOP 1
    A.PTNTIDNO,
    A.LR,
    ROUND(
        CASE WHEN ISNULL(A.ITEM1, '') = ''
        THEN (select AVG(cast('' as xml).value('sql:column("od.RIGHT01") cast as xs:decimal ?', 'decimal(28,10)') from OPERATIONDATA od)
        ELSE cast('' as xml).value('sql:column("A.ITEM1") cast as xs:decimal ?', 'decimal(28,10)')
      END, 3)
    FROM INFLABD AS A
    WHERE A.LR = 'R'
    AND A.PTNTIDNO = %s
    ORDER BY A.REGDATE DESC
Charlieface
  • 52,284
  • 6
  • 19
  • 43