avatar

目录
Sqlserver小技巧

1.获取异常信息

select ERROR_NUMBER(),ERROR_SEVERITY(),ERROR_STATE(),ERROR_PROCEDURE(), ERROR_LINE() ,ERROR_MESSAGE()

2.查看视图创建的时间:

Code
1
2
3
4
5

select [name],create_date,modify_date
FROM
sys.all_objects
where name = 'VW_F_Emp_RedeployInfoWF'

3.查看存储过程创建的时间:

Code
1
2
3
4
5
6
7

select [name],create_date,modify_date
FROM
sys.all_objects
where
type_desc = N'SQL_STORED_PROCEDURE' and
name = 'PR_CheckDeptID'

4.SQL In 语句如何返回表中不存在的值

假设表中内容如下:

ID ProjectName
1
2

执行 select * from [Table-Test] where ID in (1,3)
因为3不存在
所以sql会返回如下结果:

ID ProjectName
1

如何改写sql,让表中不存在的3也返回结果呢?
结果如下:

ID ProjectName
1
2
3 Null

实现:

Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75

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
return substring(@str,@start,@location-@start)
end

declare @canshu int
declare @str varchar(50)
--定义字符串变量
set @str='1,3,5,6,7'
declare @next int
set @next=1
Declare @Test table
(
ID int,
ProjectName varchar(50)
)
insert into @Test select * from [Table-Test]

while @next<=dbo.Get_StrArrayLength(@str,',')
begin
set @canshu = dbo.Get_StrArrayStrOfIndex(@str,',',@next)
if not exists(select * from @Test where ID =@canshu)
begin
Insert Into @Test(ID,ProjectName) values(@canshu,null)
end
set @next=@next+1
end
select * from @Test
文章作者: HJY
文章链接: https://hjy-dev.github.io/2020/02/24/Sqlserver%E5%B0%8F%E6%8A%80%E5%B7%A7/
版权声明: 本博客所有文章除特别声明外,均采用 Apache License 2.0 许可协议。转载请注明来自 Kiven Blog
打赏
  • 微信
    微信
  • 支付寶
    支付寶

评论