问题
Dev's and DBA's, I think I figured out a bug in SQL 2008 R2, unless one of you can explain the below. Can you please explain why TestID is being converted to NUMERIC instead of INT in this scenario? Please be advised that this is just a sample to show you the problem I came across while trying something bigger such as an automation script that will convert data imported from Excel or Notepad that will be nvarchar/float to the appropriate data types, int, numeric, datetime, varchar.
CREATE TABLE #CorruptData(
TestID VARCHAR(100)
);
GO
INSERT INTO #CorruptData
VALUES ('1'),
('2');
SELECT
CASE
WHEN TestID LIKE '[1-9]%' AND TestID NOT LIKE '0%' THEN CAST(TestID AS INT)
WHEN TestID LIKE '0%' THEN CAST(TestID AS NUMERIC(12,2))
END AS TestID
INTO #FixedData
FROM #CorruptData
SELECT *
FROM #FixedData
回答1:
Your 1 and 2 got converted to decimal due to the way a CASE statement returns the type:
CASE
Result Types Returns the highest precedence type from the set of types in result_expressions and the optional else_result_expression. For more information, see Data Type Precedence.
Read the full documentation: http://technet.microsoft.com/en-us/library/ms181765(v=sql.105).aspx
If you really want to see INT, then just cast whatever is returned from the CASE statement to INT:
CAST(CASE
WHEN TestID LIKE '[1-9]%' AND TestID NOT LIKE '0%' THEN CAST(TestID AS INT)
WHEN TestID LIKE '0%' THEN CAST(TestID AS NUMERIC(12,2))
END AS INT) AS TestID
回答2:
Ususaly when you are dealing with incorrent or corrupt data, you should make as less assumptions about it as possible ansd let user, who is reviewing and altering such data, decide what it is.
Also as @Louie Bao said, you cannot have same column in two or more data types. You need to select only one. As you need to keep Numeric values, your column should be NUMERIC[].
So your options are:
- Leave it as VARCHAR
- Put data into 2 different columns
INTandNumeric[] - Have a singe
NUMERICcolumn, but for display purposes convert numbers without decimal part to VARCHAR() looking as integers.
来源:https://stackoverflow.com/questions/25569569/why-is-testid-not-being-converted-to-int