1. 程式人生 > >sqlserver 如何找到主鍵為空值的欄位

sqlserver 如何找到主鍵為空值的欄位

做為主鍵,正常情況下不應該有空值,可是最近在做ogg轉化時,發現之前的sqlserver主鍵里居然有空值。

當然,他不是單主鍵,他是多主鍵組合。 在這裡紀錄一下,以便以後尋找方便。


--1.因可能多次操作,先刪除之前生成的表aaa
drop table pdaux.dbo.aaa

--2.把找到的表和欄位生成到另一個庫裡
select tablename,colname,xtype into pdaux.dbo.aaa from
(
select o.name as tablename,c.name as colname,k.colid as 欄位序號,k.keyno as 索引順序,c.xtype from sysindexes i  
join sysindexkeys k on i.id = k.id and i.indid = k.indid  
join sysobjects o on i.id = o.id  
join syscolumns c on i.id=c.id and k.colid = c.colid  
where o.xtype = 'U' 
and exists(select 1 from sysobjects where xtype = 'PK' and name = i.name)  
) as A

--3.再插入2個欄位,並把欄位型別寫進去
alter table pdaux.dbo.aaa add typename varchar(10), nullcount int
update pdaux.dbo.aaa set typename = (select top 1 name from systypes where xtype = pdaux.dbo.aaa.xtype)

--4. 字元型的欄位更新

Declare @tablename varchar(50)
Declare @colname varchar(50)
declare T_cursor01 cursor for select tablename,colname from pdaux.dbo.aaa where typename in ('varchar','nvarchar') and nullcount is null


--int,varchar,binary,datetime,numeric,tinyint,bigint,nvarchar,bit


open T_cursor01
fetch next from T_cursor01 into @tablename,@colname
while @@fetch_status=0 
begin  
Declare @sql nvarchar(500)
--Set @sql = 'Select count(0) as count from '+ @tablename +' where '+ @colname +' = '''''
Set @sql = 'update pdaux.dbo.aaa set nullcount = (select COUNT(0) from '+ @tablename +' where '+ @colname +' = '''') where tablename = '''+ @tablename +''' and colname = '''+ @colname + ''''
print @sql
execute sp_executesql @sql
fetch next from T_cursor01 into @tablename,@colname
end 
close T_cursor01 
deallocate T_cursor01


--5.非字元的欄位更新(好象有一些系統表,導致出錯,但會跳過,可執行多次)

Declare @tablename varchar(50)
Declare @colname varchar(50)
declare T_cursor01 cursor for select  tablename,colname from pdaux.dbo.aaa where typename not in ('varchar','nvarchar') and nullcount is null

--int,varchar,binary,datetime,numeric,tinyint,bigint,nvarchar,bit


open T_cursor01
fetch next from T_cursor01 into @tablename,@colname
while @@fetch_status=0 
begin  
Declare @sql nvarchar(500)
--Set @sql = 'Select count(0) as count from '+ @tablename +' where '+ @colname +' = '''''
Set @sql = 'update pdaux.dbo.aaa set nullcount = (select COUNT(0) from '+ @tablename +' where '+ @colname +' is null) where tablename = '''+ @tablename +''' and colname = '''+ @colname + ''''
print @sql
execute sp_executesql @sql
fetch next from T_cursor01 into @tablename,@colname
end 
close T_cursor01 
deallocate T_cursor01

--5.搜尋出含有主鍵為空值的表名

select distinct tablename from PDAUX.dbo.aaa where nullcount > 0


--6.拼接sql

select 'update '+ tablename +' set '+ colname +' = '' '' where '+ colname +' = '''''

from PDAUX.dbo.aaa where nullcount > 0