?
在一個 SQL Server 數據庫中,可以創建多達兩萬億個表
輸入一條 Create Table 語句 指定下列內容
1. 包含表的數據庫
2. 表的所有者
3. 表名,在同一個數據庫中和同一個所有者下,改表名必須與任何其他基表或視圖不同
4. 指定 1 到 1024 個列
5. 主鍵約束(可選)
6.1 到 250 個 Uniquer 約束(可選)
7.1 到 253 個外鍵約束(可選)
8.1 個或者多個 Check 約束 ,限制插入表中的數據(可選)
9. 存儲表的文件組(可選)
use ?databaseName
go
create ? Table ?tbName
(
???tb_id? int ? Not ? Null ? check (tb_id > 0 ),
???UserName? varchar ( 50 )?? NOT ? NULL ? CHECK (UserName <> '' )?,
???Sex?????? int ???????? not ? Null ???? Default ? 1 ?,??
??price???? Money ???? NOT ? NULL ? CHECK ((price? is ? NULL ?)? OR ?(price >= 0 )),
constraint ?tbPriKey???? Primary ? Key ?(tb_id)
)
-- --修改表--
-- 1.新增字段-
Alter ? Table ?tbName
?? add ??tbNewColumn? int ?? Null
/* 在為原來的表添加一條字段的時候需要注意的是?不允許指定該列為【?NOT?NULL?】 */
-- -2.刪除字段------
Alter ? Table ?tbName?? drop ? column ?tbNewColumn
???
-- -3.修改字段---
Alter ? Table ?tbName? Alter ? column ?tbNewColumn? char ( 30 )? null
-- --4.新建約束-------
ALTER ? Table ?tbName? ADD ? constraint ?tbNewRestrain?? check (tb_id > 0 )
-- ---5.刪除約束---------
Alter ? Table ?tbName? Drop ? constraint ?tbNewRestrain
-- -----6.新建默認值--------
Alter ? Table ?tbName? Add ? constraint ?tbNewDefault?? Default ?? ' 10 ' ? for ?tb_id
-- -----7.刪除默認值----------
Alter ? Table ?tbName? drop ? constraint ?tbNewDefault?
select ? * ? from ?tbName
2.表約束
?
?? 在我們創建表的時候,可以有選擇的制定四種類型的約束:
1. 主鍵
2. 唯一性
3. 外鍵
4. 檢查
(
s_id? int ? identity ( 1 , 1 )? primary ? key ,
s_name? varchar ( 20 )? not ? null ,
s_age? int
)
create ? table ?test
(
test_no? int ? identity ( 1 , 1 )? primary ? key ,
test_name? varchar ( 30 ),
nax_marks? int ? not ? null ? default ( 0 ),
min_marks? int ? not ? null ? default ( 0 )
)
create ? table ?marks
(
s_id? int ? not ? null ,
test_no? int ? not ? null ,
marks? int ? not ? null ? default ( 0 ),
primary ? key (s_id,test_no),
foreign ? key (s_id)? references ?student(s_id),
foreign ? key (test_no)? references ?test(test_no)
)
3. 索引以及視圖的創建
create?view??視圖名
(
字段1,
字段2,

)
as ?select?a.字段1?,a.字段2,


------ 索引的創建 --------
create?index?indexName
on?TableName
(字段1,字段2,字段3)
---- ?修改表默認字段數值 SQL SERVER
IF EXISTS ( SELECT * FROM syscolumns WHERE id = OBJECT_ID('cg_CgProcReturnBid') AND name = 'WinBidPrice' )
Begin
DECLARE @tablename VARCHAR(100), @columnname VARCHAR(100), @tab VARCHAR(100)
SET @tablename='cg_CgProcReturnBid'
SET @columnname='WinBidPrice'
declare @defname varchar(100)
declare @cmd varchar(100)
select @defname = name FROM sysobjects A JOIN sysconstraints sc ON A.id = sc.constid WHERE object_name(A.parent_obj) = @tablename AND A.xtype = 'D'AND sc.colid =(SELECT colid FROM syscolumns WHERE id = object_id(@tablename) AND name = @columnname)
select @cmd='alter table '+ @tablename+ ' drop constraint '+ @defname if @cmd is null print ''exec (@cmd)
end;
GO
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
