SQL 如何用NULL替换空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23710530/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 01:53:36  来源:igfitidea点击:

How to replace empty spaces with NULL

sqlsql-server

提问by user3004110

I have a column in sql server 2012 which contain white spaces. I want to replace these empty spaces with NULL. I have written the following query but its not working.

我在 sql server 2012 中有一个包含空格的列。我想用 NULL 替换这些空格。我已经编写了以下查询,但它不起作用。

SELECT replace(COLUMN1, '',NULL) 
FROM Orders;

How to achieve the above functionality. Thanks in advance.

如何实现上述功能。提前致谢。

回答by podiluska

Use nullif

nullif

select nullif(Column1, '') from Orders

回答by Gordon Linoff

If you want to handle the situation where the value consists of spaces or has zero length, then use ltrim()or like:

如果要处理值由空格组成或长度为零的情况,请使用ltrim()like

 select (case when value like '%[^ ]%' then value end)

Similarly,

相似地,

select (case when ltrim(value) <> '' then value end)

回答by Pranav Bilurkar

select REPLACE(ColumnName,'',NULL)as tb from TableName

回答by 001

The query below:

查询如下:

select REPLACE(ColumnName,'',NULL)as tb from TableName 

can not be used as it returns all value of this column with NULL only. Because if any parameter of Replace function is null then it returns only NULL.

不能使用,因为它仅返回此列的所有值为 NULL 的值。因为如果 Replace 函数的任何参数为 null,则它只返回 NULL。

It can be advisable to use NULLIF(columnName, '').

建议使用NULLIF(columnName, '').

回答by kapil

declare @Blank nvarchar(1)=''

声明@Blank nvarchar(1)=''

SELECT nullif(COLUMN1,@Blank) FROM Orders;

SELECT nullif(COLUMN1,@Blank) FROM 订单;

Its select all COLUMN1 records as null if thay are blank.

如果它们为空,则它选择所有 COLUMN1 记录为空。