SQL Server的基本操作

使用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
    )
 
原文地址:https://www.cnblogs.com/zjq524411/p/9837225.html