Sql Server 添加刪除字段判斷表或字段是否存在得到字段描述
增加字段
alter table docdsp add dspcode char(200)
刪除字段
ALTER TABLE table_NAME DROP COLUMN column_NAME
修改字段類(lèi)型
ALTER TABLE table_name ALTER COLUMN column_name new_data_type
改名
sp_rename
更改當(dāng)前數(shù)據(jù)庫(kù)中用戶(hù)創(chuàng)建對(duì)象(如表、列或用戶(hù)定義數(shù)據(jù)類(lèi)型)的名稱(chēng)。
語(yǔ)法
sp_rename [ @objname = ] 'object_name' ,
[ @newname = ] 'new_name'
[ , [ @objtype = ] 'object_type' ]
=======================================================
--假設(shè)要處理的表名為: tb
--判斷要添加列的表中是否有主鍵
if exists(select 1 from sysobjects where parent_obj=object_id('tb') and xtype='PK')
begin
print '表中已經(jīng)有主鍵,列只能做為普通列添加'
--添加int類(lèi)型的列,默認(rèn)值為0
alter table tb add 列名 int default 0
end
else
begin
print '表中無(wú)主鍵,添加主鍵列'
--添加int類(lèi)型的列,默認(rèn)值為0
alter table tb add 列名 int primary key default 0
end
/**************************************************************************************/
判斷table1中是否存在name字段
if exists(select * from syscolumns where id=object_id('table1') and name='name') begin
select * from people;
end
========================================================================
如果是實(shí)表可以用
if exists (select * from sysobjects where id = object_id(N'[dbo].[表名]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [dbo].[表名]--如果表存在就刪除
如果是臨時(shí)表可以用
if object_id('tempdb..##temp') is not null
drop table ##temp
說(shuō)明,如果用查找實(shí)表方法來(lái)打臨時(shí)表會(huì)找不到.發(fā)布區(qū)別對(duì)代.
==========================================================
得到表字段的描述
我一般用這個(gè)視圖
Create view fielddesc
as
select o.name as oname, c.name as cname,convert(varchar(30),p.value) as value,p.smallid as psmallid,t.name as tname
from syscolumns c
join systypes t on c.xtype = t.xtype
join sysobjects o on o.id=c.id
left join sysproperties p on p.smallid=c.colid and p.id=o.id
where o.xtype='U'
查詢(xún)時(shí):
Select * from fielddesc where oname = '你的表名'