我有一个包含超过60列的“user”表。列的名称之一是“用户名”
我想删除用户名字段为空或 NULL
的行我该怎么做?
谢谢!
答案 0 :(得分:15)
试试这个
DELETE FROM user WHERE username IS NULL;
或
DELETE FROM user WHERE username = '';
答案 1 :(得分:6)
如果要删除包含username = NULL的所有行,并且其中username为空字符串(“”)以及
然后
DELETE FROM table_name WHERE username IS NULL OR username = '';
建议首先执行SELECT
查询,条件与您要在DELETE查询中使用的WHERE
条件相同,以查看哪些行将被删除:
SELECT * FROM table_name WHERE username IS NULL OR username = "";
答案 2 :(得分:0)
在这里,我为任何类型的SQL表创建了一个脚本。请复制此存储过程并在您的环境中创建该存储过程,然后使用Table运行该存储过程。
exec [dbo].[SP_RemoveNullValues] 'Your_Table_Name'
存储过程
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--akila liyanaarachchi
Create procedure [dbo].[SP_RemoveNullValues](@PTableName Varchar(50) ) as
begin
DECLARE Cussor CURSOR FOR
SELECT COLUMN_NAME,TABLE_NAME,DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = @PTableName
OPEN Cussor;
Declare @ColumnName Varchar(50)
Declare @TableName Varchar(50)
Declare @DataType Varchar(50)
Declare @Flage int
FETCH NEXT FROM Cussor INTO @ColumnName,@TableName,@DataType
WHILE @@FETCH_STATUS = 0
BEGIN
set @Flage=0
If(@DataType in('bigint','numeric','bit','smallint','decimal','smallmoney','int','tinyint','money','float','real'))
begin
set @Flage=1
end
If(@DataType in('date','atetimeoffset','datetime2','smalldatetime','datetime','time'))
begin
set @Flage=2
end
If(@DataType in('char','varchar','text','nchar','nvarchar','ntext'))
begin
set @Flage=3
end
If(@DataType in('binary','varbinary'))
begin
set @Flage=4
end
DECLARE @SQL VARCHAR(MAX)
if (@Flage in(1,4))
begin
SET @SQL =' update ['+@TableName+'] set ['+@ColumnName+']=0 where ['+@ColumnName+'] is null'
end
if (@Flage =3)
begin
SET @SQL =' update ['+@TableName+'] set ['+@ColumnName+'] = '''' where ['+@ColumnName+'] is null '
end
if (@Flage =2)
begin
SET @SQL =' update ['+@TableName+'] set ['+@ColumnName+'] ='+'''1901-01-01 00:00:00.000'''+' where ['+@ColumnName+'] is null '
end
EXEC(@SQL)
FETCH NEXT FROM Cussor INTO @ColumnName,@TableName,@DataType
END
CLOSE Cussor
DEALLOCATE Cussor
END