Sql_server基本操作

a最簡單發表於2018-08-28

使用Sql_server建立表,檢視,觸發器,儲存過程,函式等基本操作。

 

create table test1(                  /* 建立一個表 */
    num int
)   

alter table test1                    /* 修改表 */
alter column num int not null        /* 修改某一列 */


alter table test1                    /* 修改表 */
add constraint pk_num                /* 新增約束 */
primary key(num);                    /* 主鍵約束 */


create trigger insert_test1          /* 建立觸發器 */
on test1 for insert                  /* 當test1有新增資料時觸發 */
as                                   /* as 以後時sql語句 */
begin
    print `success!`
end

select * into test1Bak               /* 建立備份表 */
from test1
where 1 = 2                          /* 備份為空表 */



create view s1                      /* 建立檢視 s1 */
        as                           /* 注意,這個as不可省略 */    
        select *from jk


create proc procSumByPurchase                
    @Gname nvarchar(50),                           /* 指定多個引數 */
    @name nvarchar(50),
    @num int output                                /* 輸出引數 */
as
begin
    select @num = (
        select sum(s.Sell_num)
        from Sell s inner join Goods g
        on g.Goo_no = s.Goo_no
        group by g.Goo_name, s.Sell_date, g.Pro_name
        having g.Goo_name = @name
        and g.Pro_name = @Gname
        and    year(s.Sell_date) = 2018            /* date篩選年份 */
        and month(s.Sell_date) = 1                 /* date篩選月份 */
    )
end

declare @num1 int                        
exec procSumByPurchase `聯想公司`, `拯救者15.6英寸輕薄遊戲本`, @num1 output
select `SumNum` = str(@num1)                    /* 將返回的 int 型轉變成 字串 */



create function Purchase_Total(@start datetime,        /* 自定義函式 */
    @last datetime)                                    /* 可多個引數 */
    returns table                                      /* 返回值型別,這裡為表格 */
as                                                     /* as以後為 sql 語句 */
    return(                                            /* 最後為返回型別 */
        select *
        from Purchase p
        where p.Pur_date >= @start
        and p.Pur_date <= @last
    )