如何刪除所有紀錄都為NULL的表

2021-04-24 12:52:57 字數 3049 閱讀 7415

這個需求是今天看到一網友在論壇提出的問題,這裡的紀錄為null,是指的紀錄為"null"值,而並不是表的紀錄數為0,所以我們可以通過checksum函式來實現這個需求,下面是實現的demo:

--執行環境:sql server 2005

use 

tempdb

go set 

nocount 

on if 

object_id

('t1'

) is 

not null

drop table 

t1 if 

object_id

('t2'

) is 

not null

drop table 

t2 if 

object_id

('t3'

) is 

not null

drop table 

t3 --建立測試環境

create table 

t1 (

col1 

int,

col2 

int,

col3 datetime    

) create table 

t2 (

col1 

int,

col2 

varchar(10

), col3 float

) create table 

t3 (

col1 decimal(10

,2), col2 

nchar(10

) )

go --插入測試資料

insert 

t1 select 

null,null,null 

union 

all 

select 

null,null,null

insert 

t2 select 

null,null,null

insert 

t3 select 

null,null

union 

all 

select 

null,

n'test'

go --刪除所有紀錄為null的表

declare 

@table_name 

sysname

, @sql 

nvarchar

(1000

) declare 

curtest 

cursor 

local static read_only forward_only

for

select 

name

from 

sys.tables

where 

name 

not like 

'#%'

and 

name 

not in(

'msdistributor_access'

) open 

curtest

fetch 

next 

from 

curtest 

into 

@table_name

while 

@@fetch_status=0

begin

set 

@sql 

= n'

if not exists(

select *

from ' 

+  @table_name 

+  n'

where checksum(*) <> 2147483511

) drop table  ' 

+ @table_name 

+ n'

' exec 

sp_executesql 

@sql

fetch 

next 

from 

curtest 

into 

@table_name

end

close 

curtest

deallocate 

curtest

go select 

* from 

t1   

--丟擲錯誤

select 

* from 

t2   

--丟擲錯誤

select 

* from 

t3 go

--刪除測試環境

if object_id

('t1'

) is 

not null

drop table 

t1 if 

object_id

('t2'

) is 

not null

drop table 

t2 if 

object_id

('t3'

) is 

not null

drop table 

t3 從這個例子可以看到,t1,t2的表已經被刪除,因為它的所有紀錄都為null.

雖然它實現了這個需求,但可能存在以下隱患:

1:checksum()函式不能用於一些非可比資料型別:textntextxmlimagecursor

2:如果表上存在一些外來鍵約束,直接刪除,會丟擲錯誤

查詢某個紀錄的所有父類的紀錄!

category 表 categoryid categoryname parentid 1 新聞 0 2 文化 0 3 國內 1 4 國際 1 5 廣東 3 6 廣西 3 7 廣州 5 當 categoryid 輸入 7 時,顯示以下結果 1 新聞 0 3 國內 1 5 廣東 3 7 廣州 5 cr...

刪除MYSQL中的紀錄 如何 刪除資料庫中的記錄

如何 刪除資料庫中的記錄 08 18 2008 本文內容 更新 2007 年 11 月 要從資料庫中刪除記錄,請使用 tableadapter.update 方法或 tableadapter.delete 方法。或者,如果您的應用程式不使用 tableadapters,您就可以使用命令物件從資料庫中...

統計所有帶有null的特徵

以下 僅僅適用於numerical特徵,不適用於category特徵 如下 統計有缺失值的特徵列 np.set printoptions threshold 2000 全部輸出 pd.set option display.max colwidth 2000 全部輸出 pd.set option ma...