常用字符串分割函数:
--根据指定字符分割字符串
CREATE FUNCTION [dbo].[fun_SplitStringToTable] ( @string NVARCHAR(max), @splitChar NVARCHAR(max) ) RETURNS @tb TABLE ( SubChar NVARCHAR(max) ) AS BEGIN DECLARE @start INT DECLARE @next INT SET @start = 1 SET @next = CHARINDEX(@splitChar, @string, @start) IF(@next > 0) BEGIN WHILE(@next > 0) BEGIN INSERT INTO @tb VALUES(SUBSTRING(@string, @start, @next - @start)) SET @start = @next + LEN(@splitChar) SET @next = CHARINDEX(@splitChar, @string, @start) IF(@next = 0 AND @start <= LEN(@string)) BEGIN INSERT INTO @tb VALUES(SUBSTRING(@string, @start, LEN(@string) - @start + 1)) END END END ELSE BEGIN INSERT INTO @tb VALUES(@string) END RETURN END GO
--获取通过指定字符分组的字符串中某一分组的内容
CREATE FUNCTION [dbo].[GetSplitOfIndex] ( @SplitString NVARCHAR(max), @SplitChar VARCHAR(10), @Index INT ) RETURNS NVARCHAR(max) AS BEGIN DECLARE @Start INT DECLARE @Location INT DECLARE @i INT SET @SplitString = LTRIM(RTRIM(@SplitString)) SET @Start = 1 SET @Location = CHARINDEX(@SplitChar, @SplitString, @Start) SET @i = 1 --@表示循环次数 WHILE(@Location <> 0 AND @Index > @i) BEGIN SET @Start = @Location + LEN(@SplitChar) SET @Location = CHARINDEX(@SplitChar, @SplitString, @Start) SET @i = @i + 1 END IF @Location = 0 SET @Location = LEN(@SplitString) + 1 RETURN SUBSTRING(@SplitString, @Start, @Location - @Start) END GO
sql中三种数据插入语句写法:
INSERT INTO table1(id, name, address) VALUES(1, ygl, 'beijing')
insert into table2(id, name, address) select id,name,address from table1
select id, name, address into table2 from table1 --会自动创建table2
动态sql
--1、执行普通sql语句
EXEC('select * from zhy_Users')
Exec sys.sp_executesql N'select * from zhy_Users' --sql语句前面一定要加N
--2、字段名、表名、数据库名作为变量时,必须用动态sql
DECLARE @ColumnName VARCHAR(10)
SET @ColumnName = 'UserName'
EXEC('select ' + @ColumnName + ' from zhy_Users')
DECLARE @SqlQuery VARCHAR(1000)
SET @SqlQuery = 'select ' + @ColumnName + ' from zhy_Users'
EXEC(@SqlQuery)
--下面语句会报错
--EXEC sys.sp_executesql @SqlQuery
--当@SqlQuery定义为Nvarchar类型时能执行成功
--返回动态sql中的值
DECLARE @num INT
DECLARE @sqls NVARCHAR(2000)
SET @sqls = 'select @a=count(*) from zhy_Users'
EXEC sys.sp_executesql @sqls,N'@a int output',@num OUTPUT
SELECT @num
sql语句中单引号的处理:
在sql语句中单引号通常是字符串的分界点,如:select * from table where name like 'xxx';若要在字符串中表示单引号,则需要加多一个单引号,即在字符串中用两个单引号表示一个单引号,如:select * from table where name like 'x''xx'
sql中DATEPART ( datepart ,date )
函数的理解:
使用datename(dw,date)可以返回汉字形式的星期
获取指定日期
获取当前月的第一天:
SELECT DATEADD(MM, DATEDIFF(MM, 0, GETDATE()), 0)
获取上月的最后一天:(有一点要记住,在Sql Server中时间是精确到3毫秒。这就是为什么我需要减去3毫秒来获得我要的日期和时间)
SELECT DATEADD(ms, –3, DATEADD(MM, DATEDIFF(MM, 0, GETDATE()), 0))
获取当前周的第一天:(系统默认周日是一周的第一天,为了将周一当作第一天,所以将GETDATE()减去一天)
SELECT DATEADD(WK, DATEDIFF(WK, 0, DATEADD(DD, -1, GETDATE())), 0)
获取当前周的最后一天:
SELECT DATEADD(MS, –3, DATEADD(WK, DATEDIFF(WK, 0, DATEADD(DD, -1, GETDATE())), 0))