Convert INT column values to an empty string using ISNULL

二次信任 提交于 2019-12-07 10:03:55

问题


I need to convert column ID of INT data type to a empty string ['']. I should not modify the source column data type, but need to convert it in my transformation in the other table. The ID column is "nullable" as it has null in it.This is my code.

CREATE TABLE #V(ID INT) ;

INSERT INTO #V 
    VALUES (1),(2),(3),(4),(5),(NULL),(NULL) ;

 SELECT CASE WHEN CAST(ISNULL(ID,'') AS VARCHAR(10)) = '' THEN '' ELSE ID END AS ID_Column
 FROM  #V;

this returns:

ID_Column
1
2
3
4
5
NULL
NULL

when I modify my CASE statement it as follows:

CASE WHEN CAST(ISNULL(ID,'') AS VARCHAR(10)) = '' THEN '' ELSE ID END AS  ID_Column

it returns:

ID_Column
1
2
3
4
5
0
0

回答1:


Is this what you want?

select coalesce(cast(id as varchar(255)), '')
from #v;

You have to turn the entire result column into a single column. If you want a blank value, then the type is some sort of character string.

In your examples, the else id means that the result from the case is an integer, which is why you are getting either 0 or NULL.



来源:https://stackoverflow.com/questions/39937037/convert-int-column-values-to-an-empty-string-using-isnull

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!