SQL Server函数

-- 查询没有地址的人(地址为null)
-- null值不能使用 = 比较
-- is是   is not不是
select * from stu where address is null;

--查询有邮箱的
select * from stu where email is not null;

--查询有家有邮箱的
--java中多个条件用或者和并且
--sql中没有特殊符号  or或者 and并且
select * from stu 
where address is not null and email is not null;

--查询性别 (distinct 去除重复值)
select distinct(sex) from stu;

--排序 order by(根据年龄,默认是升序)
-- 升序 asc
-- 降序 desc

select * from stu order by birthday desc;

-- 查看年龄大的前10人

select top 10 * from stu order by birthday;

-- 查看年龄大的前50%
-- percent 就是 %

select top 50 percent * from stu 
order by birthday;

--------------------函数,方法
 
-- 查找特定字符的位置
select charindex('c','123a');

--名字里面带张的人
select * from stu where charindex('李',sname)!=0;

--len 字符的个数
select len('你好');

-- 查询学生表中所有的名字为两个字的
select * from stu where len(sname)=2;

--大写 upper 和小写 lower 函数
select upper('abc');
select lower('ABC');

-- 显示每个学生的名字和邮箱
-- 将邮箱大写
select sname,upper(email) from stu;

-- 清除空格
select ltrim('      你好');
select rtrim('你好      ');

-- 取字符
select right('你好啊',1);
select left('你好啊',1);

-- 取出学生表中姓为 李 的人
select * from stu where left(sname,1)='李';

-- 替换

replace 替换一个字符串中的字符 

select replace('abcd','b','c');

返回:accd

--将天津市变成经天市
update stu 
set address=replace(address,'天津市','经天市');

---------------------------------

--当前日期
select getdate();

-- 增加日期
select dateadd(mm,3,getdate());

--求当前的55分钟之后是多久
select dateadd(mi,50,getdate());

--显示所有学生数据,在生日上面+100年
select sname,birthday,dateadd(yyyy,100,birthday)
from stu;

--日期相减
select dateadd(dd,-1,getdate());

--日期求差
select datediff(yyyy,'2020/1/1',getdate());

--显示每个学生的年龄
select sname,birthday,
datediff(yyyy,birthday,getdate()),
datediff(dd,birthday,getdate())
from stu;

-- year年
-- month 月
-- day 日
select year(getdate());
select month(getdate());
select day(getdate());

--求1998年出生的学生
select * from stu where year(birthday)=2020;

----------------------------------

--绝对值
select abs(-1);

-- 求整
-- 1.01 -> 2,1

--向上
select ceiling(1.9999999999999999);

返回:2
--向下
select floor(1.99999999999999999999);

返回:1
--四舍五入
select round(1.3,0);

select floor(-1.9);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 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
SQL Server函数是用于在T-SQL中执行特定任务的代码块。根据其性质,函数可以分为确定性函数和非确定性函数。确定性函数在相同的参数下始终返回相同的结果,而非确定性函数的结果可能会受到其他因素的影响。\[1\] 非确定性函数在使用自定义函数等特定的SQL编程对象时有一些限制。这是因为SQL Server需要显式执行这些函数,而不能依赖于缓存或预编译的可执行对象。因此,在构建可重用的编程对象时,理解函数的确定性与非确定性是很重要的。\[2\] 此外,SQL Server还提供了一些工具函数,用于返回服务器和数据库的配置细节,以及返回不同对象属性状态的通用和专用函数。这些函数封装了对系统表和用户数据库的查询,建议使用这些系统函数而不是自己创建对系统表的查询,以防将来SQL Server版本对模式进行更改。\[3\] 总结来说,SQL Server函数是用于执行特定任务的代码块,可以分为确定性函数和非确定性函数。在使用自定义函数等特定的SQL编程对象时,对非确定性函数有一些限制。此外,SQL Server还提供了一些工具函数,用于返回服务器和数据库的配置细节。 #### 引用[.reference_title] - *1* *2* *3* [SQL函数说明大全](https://blog.csdn.net/leamonjxl/article/details/6309864)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值