2

I got a error when i am trying to execute below query. can anyone sort out this would appreciated.

DECLARE @TABLE TABLE(ID INT,CATEGORY VARCHAR(30),VALUE VARCHAR(30))
INSERT INTO @TABLE
SELECT 1,'A','5'
UNION ALL 
SELECT 2,'B','6'
UNION ALL
SELECT 3,'C','VAL'
UNION ALL
SELECT 4,'D','HSD'

DECLARE @TABLE1 TABLE(ID INT,CATEGORY VARCHAR(30),VALUE VARCHAR(30))
INSERT INTO @TABLE1
SELECT 1,'A','5.0'
UNION ALL 
SELECT 2,'B','6.0'
UNION ALL
SELECT 3,'C','VAL'
UNION ALL
SELECT 4,'D','HSD'

SELECT
    A.ID,
    A.CATEGORY,
    A.VALUE
FROM @TABLE A, @TABLE1 B
WHERE
    CASE ISNUMERIC(A.VALUE) WHEN 1 THEN CAST (A.VALUE AS NUMERIC)
                                   ELSE A.VALUE END=CASE ISNUMERIC(B.VALUE) WHEN 1
                                   THEN CAST (B.VALUE AS NUMERIC) ELSE B.VALUE END

2 Answers 2

7

I believe the error you are getting is being caused by that your CASE expressions in the WHERE clause have branches with different types, namely text and numeric. To fix this, you need to make all branches be the same type. Making everything numeric won't work because of the text, but we can make everything text instead.

For the case of numeric data, you don't even have the same type of data there either. To get around this, you can cast the numeric data to a common decimal format before converting back again to text:

WHERE
    CASE WHEN ISNUMERIC(A.VALUE) = 1
         THEN CONVERT(VARCHAR, CAST(A.VALUE AS DECIMAL(10,2)))
         ELSE A.VALUE END =
    CASE WHEN ISNUMERIC(B.VALUE) = 1
         THEN CONVERT(VARCHAR, CAST(B.VALUE AS DECIMAL(10,2)))
         ELSE B.VALUE END

The best long term solution for you would be to not mix text and numeric data in the same column. I don't know why this answer was downvoted, as it is working code which answers the original question.

Output:

enter image description here

Demo here:

Rextester

Sign up to request clarification or add additional context in comments.

Comments

-2

One Columns can only be one type..

You can't put two type "NUMERIC" and "varchar(30)" in one column...

Best way is cast to one type. Seems varchar(30) is a better choice.

SELECT
    A.ID,
    A.CATEGORY,
    A.VALUE
FROM @TABLE A, @TABLE1 B
WHERE
    ISNUMERIC(A.VALUE) = ISNUMERIC(B.VALUE)
    and 
    CASE ISNUMERIC(A.VALUE) WHEN 1 THEN CAST(CAST(A.VALUE AS NUMERIC) as VARCHAR(30)) ELSE A.VALUE END
    = CASE ISNUMERIC(B.VALUE) WHEN 1 THEN cast(CAST(B.VALUE AS NUMERIC) as VARCHAR(30)) ELSE B.VALUE END

1 Comment

I don't think this is what the OP wants, because none of the numeric data is matching: See here.

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.