C#SqlServer学习(六)

1.SqlHelper的封装

    ->参数化处理
    ->DRY原则
        ->ExcuteNonQuery()
        ->ExcuteScalar()
        ->ExcuteReader()
        ->ExcuteTable()
       SqlHelper + app.config 
    


2.Case的用法

    ->使用方法一:(类似C#中的Case的用法)
        ->语法:
            Case  表达式
                when 值1  then  返回值
                when 值1  then  返回值
                ....
            End
        
    ->使用方法二:(类似C#中的多个if else)
        ->语法
            Case 
                When 表达式 then 返回值
                When 表达式 then 返回值
                else 值
            end              

3.SQL控制语句

    ->定义变量:declare
        ->给变量赋值:
            ->set @参数名=值
            ->select @参数名=值
        
    ->打印 : Print
    ->IF ELSE
        ->语法格式:
        if(表达式) 
        begin 
            SQL语句
        end   
        else 
        begin 
            语句
        end        
    ->WHILE
        ->语法:
            While(表达式)
            begin
                SQL语句
            end

4.子查询

    ->把一个查询结果作为一个表来使用,就是子查询
    
    ->把一个查询结果作为 一个 表达式进行使用就是子查询。
    
    案例:        
        --查询顾客表中属于同一家公司超过两个顾客的公司名称        
        
        select CompanyName,count(*) as 个数  from SalesLT.Customer group by CompanyName having count(*)>2

        --查询顾客表中  相同公司人数最多的 顾客信息
        
                select * from SalesLT.Customer where CompanyName=(
            select top 1 CompanyName from SalesLT.Customer group by CompanyName order by count(*) desc
        )

        --查询 相同公司人数最多的顾客的订单信息
        select * from SalesLT.SalesOrderHeader where CustomerID
            in(
                select CustomerID from SalesLT.Customer where CompanyName=(
            select top 1 CompanyName from SalesLT.Customer group by CompanyName order by count(*) desc)
            )

        --查询山东省的所有的城市信息
        use 0413DB
        go

        select areaId from AreaFull where AreaPId =(select AreaId from AreaFull where AreaName=N'山东省')
        --查询山东省中所有县级市的
        select * from AreaFull where AreaPId in(
            select areaId from AreaFull where AreaPId =(select AreaId from AreaFull where AreaName=N'山东省')
        )

        --查询山东省中的所有的县
        select * from AreaFull where AreaPId in(
            select areaId from AreaFull where AreaPId =(select AreaId from AreaFull where AreaName=N'山东省')
        ) and AreaName like N'%县'

 

5.分页SQL语句

    ->Row_Number函数的分页使用
    ->双Order排序 分页法【越过多少条,取多少条数据】
    
    

6.表链接

    ->Inner Join
        ->查询员工出差的信息。
    ->Right Join
        ->查询所有员工的信息,如果有出差信息则显示出差信息。
    ->Left Join
    ->Full Join
        ->查询所有员工的信息和所有的出差信息,
    ->Cross Join
        ->查询所有员工和所有职位的组合情况


7.索引

    ->索引就是表的目录。 提高查询效率。
    ->创建索引        
        ->索引的分类
            ->聚簇索引:索引的存储顺序跟数据的存储顺序一致。
            ->非聚簇索引:索引指向聚簇索引或者是数据存储的磁盘位置。
        ->语法
            ->非聚集索引
                ->CREATE  INDEX  索引名  ON 表名(列名)
            ->创建唯一非聚集索引
                ->CREATE UNIQUE INDEX 索引名 ON 表名(列名)
            ->创建聚集索引
                ->CREATE TABLE t1 (a int, b int, c AS a/b); 
                CREATE UNIQUE CLUSTERED INDEX Idx1 ON t1(c); 
                INSERT INTO t1 VALUES (1, 0);
            
    ->使用索引的条件:
        ->经常查询的字段,经常进行数据筛选的列
    
    ->索引失效:
        ->where条件后面使用了 <> 、not in 、not exist、!= 、Or等
        ->对列使用了函数处理 类型转换函数 convert  cast
        ->隐式转换使索引失效:
            ->错误的例子:select * from test where tu_mdn=13333333333;
            ->正确的例子:select * from test where tu_mdn='13333333333';
        ->对索引列进行运算导致索引失效,我所指的对索引列进行运算包括(+,-,*,/,! 等)
            ->错误的例子:select * from test where id-1=9;
            ->正确的例子:select * from test where id=10;
        ->like查询是以%开头
        ->在Where子句中使用IS NULL或者IS NOT NULL

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
--计算当前月的实际天数 Create FUNCTION dbo.CalcDaysOfMonth (@time varchar(6)) RETURNS int AS BEGIN DECLARE @Days int DECLARE @Month int DECLARE @Year int SET @Year=SUBSTRING(@time,1,4) SET @Month=SUBSTRING(@time,5,6) if( @Month='1' OR @Month='3' OR @Month='5' OR @Month='7' OR @Month='8' OR @Month='10' OR @Month='12' ) set @Days=31 else if( @Month='4' OR @Month='6' OR @Month='9' OR @Month='11' ) set @Days=30; else if(@Year%400=0 OR (@Year%4=0 AND @Year%100<>0)) set @Days=29 else set @Days=28 RETURN(@Days) END --确定某年某月有多少天 Create FUNCTION DaysInMonth ( @date datetime ) Returns int AS BEGIN RETURN Day(dateadd(mi,-3,DATEADD(m, DATEDIFF(m,0,@date)+1,0))) END --哪一天是输入时间的星期一 Create FUNCTION MondayInDate ( @date datetime ) RETURNS DATETIME AS BEGIN RETURN DATEADD(week, DATEDIFF(week,0,@date),0) END --输入时间的季度的第一天 Create FUNCTION QuarterInDate ( @date datetime ) RETURNS DATETIME AS BEGIN RETURN DATEADD(quarter, DATEDIFF(quarter,0,@date), 0) END --输入时间的季度的天数 Create FUNCTION QuarterDaysInDate ( @date datetime ) RETURNS INT AS BEGIN declare @m tinyint,@time SMALLDATETIME select @m=month(@date) select @m=case when @m between 1 and 3 then 1 when @m between 4 and 6 then 4 when @m between 7 and 9 then 7 else 10 end select @time=datename(year,@date)+'-'+convert(varchar(10),@m)+'-01' return datediff(day,@time,dateadd(mm,3,@time)) END --按指定符号分割字符串,返回分割后的元素个数,方法很简单,就是看字符串中存在多少个分隔符号,然后再加一,就是要求的结果。 Create function Get_StrArrayLength ( @str varchar(1024), --要分割的字符串 @split varchar(10) --分隔符号 ) returns int as begin declare @location int declare @start int declare @length int set @str=ltrim(rtrim(@str)) set @location=charindex(@split,@str) set @length=1 while @location<>0 begin set @start=@location+1 set @location=charindex(@split,@str,@start) set @length=@length+1 end return @length END --按指定符号分割字符串,返回分割后指定索引的第几个元素,象数组一样方便 Create function Get_StrArrayStrOfIndex ( @str varchar(1024), --要分割的字符串 @split varchar(10), --分隔符号 @index int --取第几个元素 ) returns varchar(1024) as begin declare @location int declare @start int declare @next int declare @seed int set @str=ltrim(rtrim(@str)) set @start=1 set @next=1 set @seed=len(@split) set @location=charindex(@split,@str) while @location<>0 and @index>@next begin set @start=@location+@seed set @location=charindex(@split,@str,@start) set @next=@next+1 end if @location =0 select @location =len(@str)+1 --这儿存在两种情况:1、字符串不存在分隔符号 2、字符串中存在分隔符号,跳出while循环后,@location为0,那默认为字符串后边有一个分隔符号。 return substring(@str,@start,@location-@start) END select dbo.Get_StrArrayStrOfIndex('8,9,4','',4) --结合上边两个函数,象数组一样遍历字符串中的元素 create function f_splitstr(@SourceSql varchar(8000),@StrSeprate varchar(100)) returns @temp table(F1 varchar(100)) as begin declare @ch as varchar(100) set @SourceSql=@SourceSql+@StrSeprate while(@SourceSql<>'') begin set @ch=left(@SourceSql,charindex(',',@SourceSql,1)-1) insert @temp values(@ch) set @SourceSql=stuff(@SourceSql,1,charindex(',',@SourceSql,1),'') end return end select * from dbo.f_splitstr('1,2,3,4',',') --全角和半角转换函数 Create FUNCTION f_Convert( @str NVARCHAR(4000), --要转换的字符串 @flag bit --转换标志,0转换成半角,1转换成全角 )RETURNS nvarchar(4000) AS BEGIN DECLARE @pat nvarchar(8),@step int,@i int,@spc int IF @flag=0 Select @pat=N'%[!-~]%',@step=-65248, @str=REPLACE(@str,N' ',N' ') ELSE Select @pat=N'%[!-~]%',@step=65248, @str=REPLACE(@str,N' ',N' ') SET @i=PATINDEX(@pat COLLATE LATIN1_GENERAL_BIN,@str) WHILE @i>0 Select @str=REPLACE(@str, SUBSTRING(@str,@i,1), NCHAR(UNICODE(SUBSTRING(@str,@i,1))+@step)) ,@i=PATINDEX(@pat COLLATE LATIN1_GENERAL_BIN,@str) RETURN(@str) END GO declare @s1 varchar(8000) select @s1='中  2-3456a78STUVabn中国opwxyz' select dbo.f_convert(@s1,0),dbo.f_convert(@s1,1) 函数返回值是表 create table test(id int primary key,name char(10)) insert into test values(1,'test1') insert into test values(2,'test2') insert into test values(3,'test3') insert into test values(4,'test4') 1、标量函数 create function return_count() returns int as begin declare @count int select @count=count(*) from test return @count end --调用 select dbo.return_count() cont --count为显示的列头 --运行结果 --count --4 2、内嵌表值函数 create function return_test() returns table as --begin 内联表值函数不能用begin-end return select name from test --end --调用 select * from return_test() --运行结果 --name --test1 --test2 --test3 --test4 3、多语句表值函数 create function return_test_multi() returns @temp table(id int,name char(10)) as begin insert into @temp select * from test where id in(1,2) return --记住,一定不要忘记写return end --调用 select * from dbo.return_test_multi() --运行结果 --id name --1 test1 --2 test2 在查询结果中增加一个自动增长的ID select id=identity(int, 1, 1), * into #T from testTable select * from #T drop table #T sql删除重复的记录 打开测试数据库test,并以表w01为例,将下面的SQL语句放入sql2000查询分析器中,一段一段执行即可看到效果 ---在sql2000下创建测试数据表 if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[w01]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [dbo].[w01] ---在sql2005下创建测试数据表,如果是sql2005则用本段来判断数据表是否存在 ---if exists(select 1 from sys.tables where name='w01') ---drop table w01 ----开始创建测试数据库 GO create table w01(gs903 varchar(32),gs1002 varchar(32)) insert into w01 select '1','a' union all select '1','a' union all select '1','a' union all select '2','a' union all select '2','e' union all select '3','b' union all select '3','d' go select * from w01 go ---为表w01添加一个可以表示唯一标示的自增字段ID alter table w01 add [ID] [int] IDENTITY (1, 1) NOT FOR REPLICATION NOT NULL ---查询删除前的数据和记录数:7 select * from w01 select count(*) from w01 ---查询具有重复记录的所有记录;3 select gs903,gs1002,count(*) as count from w01 group by gs903,gs1002 having count(*)>1 order by count desc ---删除重复的数据:2行 delete from w01 where id not in (select max(id) from w01 group by gs903,gs1002) ---看看删除后还有没有重复记录:0 select gs903,gs1002,count(*) as count from w01 group by gs903,gs1002 having count(*)>1 order by count desc ---删除后的数据和记录数:7-2=5 select * from w01 select count(*) from w01 用SQL语句添加删除修改字段 增加字段 alter table docdsp add dspcode char(200) 删除字段 Alter TABLE table_NAME Drop COLUMN column_NAME 修改字段类型 Alter TABLE table_name Alter COLUMN column_name new_data_type 改名 sp_rename 更改当前数据库中用户创建对象(如表、列或用户定义数据类型)的名称。 语法 sp_rename [ @objname = ] 'object_name' , [ @newname = ] 'new_name' [ , [ @objtype = ] 'object_type' ] --假设要处理的表名为: tb --判断要添加列的表中是否有主键 if exists(select 1 from sysobjects where parent_obj=object_id('tb') and xtype='PK') begin print '表中已经有主键,列只能做为普通列添加' --添加int类型的列,默认值为0 alter table tb add 列名 int default 0 end else begin print '表中无主键,添加主键列' --添加int类型的列,默认值为0 alter table tb add 列名 int primary key default 0 end

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

挑战不可

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值