【叶子函数分享四十一】SQL位移运算函数
2011-03-22 23:03
281 查看
-- =============================================
-- Author: <maco_wang>
-- Create date: <2011-03-22>
-- Description: <SQL位移运算函数>
-- =============================================
go
--创建函数
create function displacement(@n as bigint,@m as varchar(3))
returns int
as
begin
declare @maco varchar(50);set @maco=''
declare @i int
declare @x int
declare @s int
while (@n<>0)
begin
set @maco=@maco+convert(char(1),@n%2)
set @n=@n/2
end
set @maco=reverse(@maco)
set @maco=RIGHT('0000'+@maco,4)
set @s=LEN(@maco)
set @i=convert(int,RIGHT(@m,1))
set @x=1
if LEFT(@m,2)='<<'
begin
while(@x<=@i)
begin
select @maco=@maco+'0'
select @x=@x+1
end
select @maco=RIGHT(@maco,@s)
end
if LEFT(@m,2)='>>'
begin
while(@x<=@i)
begin
select @maco='0'+@maco
select @x=@x+1
end
select @maco=LEFT(@maco,@s)
end
set @i=LEN(@maco)
set @s=0
while(@i>0)
begin
if SUBSTRING(@maco,LEN(@maco)-@i+1,1)='1'
begin
select @s=@s+POWER(2,convert(float,@i-1))
end
select @i=@i-1
end
return @s
end
--测试示例
select dbo.displacement(1,'<<3')
select dbo.displacement(8,'>>1')
select dbo.displacement(12,'>>3')
--运行结果
/*
8
4
1
*/
-- Author: <maco_wang>
-- Create date: <2011-03-22>
-- Description: <SQL位移运算函数>
-- =============================================
go
--创建函数
create function displacement(@n as bigint,@m as varchar(3))
returns int
as
begin
declare @maco varchar(50);set @maco=''
declare @i int
declare @x int
declare @s int
while (@n<>0)
begin
set @maco=@maco+convert(char(1),@n%2)
set @n=@n/2
end
set @maco=reverse(@maco)
set @maco=RIGHT('0000'+@maco,4)
set @s=LEN(@maco)
set @i=convert(int,RIGHT(@m,1))
set @x=1
if LEFT(@m,2)='<<'
begin
while(@x<=@i)
begin
select @maco=@maco+'0'
select @x=@x+1
end
select @maco=RIGHT(@maco,@s)
end
if LEFT(@m,2)='>>'
begin
while(@x<=@i)
begin
select @maco='0'+@maco
select @x=@x+1
end
select @maco=LEFT(@maco,@s)
end
set @i=LEN(@maco)
set @s=0
while(@i>0)
begin
if SUBSTRING(@maco,LEN(@maco)-@i+1,1)='1'
begin
select @s=@s+POWER(2,convert(float,@i-1))
end
select @i=@i-1
end
return @s
end
--测试示例
select dbo.displacement(1,'<<3')
select dbo.displacement(8,'>>1')
select dbo.displacement(12,'>>3')
--运行结果
/*
8
4
1
*/
相关文章推荐
- 【叶子函数分享二十九】完善SQL农历转换函数
- 【叶子函数分享三十三】根据进舍位或四舍五入来求值
- 【叶子函数分享十二】根据身份证得到生日函数
- [MSSQL]【叶子函数分享二十八】根据年度判断是否是闰年
- 【叶子函数分享三十七】求字符串中汉字的个数
- 【叶子函数分享四十九】生成两个时间之间的所有日期
- 【叶子函数分享三十】SQL简繁转换函数
- 【叶子函数分享十三】根据身份证计算性别函数
- 【叶子函数分享四十八】根据年得到所有星期日的日期
- 【叶子函数分享十二】根据身份证得到生日函数
- 【叶子函数分享二十一】检查给定串是否存在于由区间及点集的结合内
- 【叶子函数分享四十】将一个正整数分解为m个2的n次方的和
- 【叶子函数分享四十九】生成两个时间之间的所有日期
- 【叶子函数分享五十四】汉字转拼音函数
- 【叶子函数分享十四】将身份证的15位号码升级为18位
- 【叶子函数分享五十八】固定长度添加分隔符函数
- 【叶子函数分享十一】取汉字首字母的两个函数
- 【叶子函数分享十三】根据身份证计算性别函数
- 【叶子函数分享二十二】根据日期返回星座
- 【叶子函数分享五十】无序字符比较函数