SQL Server 将整数转换为二进制字符串 [英] SQL Server Convert integer to binary string

查看:104
本文介绍了SQL Server 将整数转换为二进制字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道 SQL 中是否有一种简单的方法可以将整数转换为其二进制表示形式,然后将其存储为 varchar.

I was wondering if there was an easy way in SQL to convert an integer to its binary representation and then store it as a varchar.

例如 5 将转换为101"并存储为 varchar.

For example 5 would be converted to "101" and stored as a varchar.

推荐答案

以下可以编码成一个函数.您需要修剪前导零以满足您的问题要求.

Following could be coded into a function. You would need to trim off leading zeros to meet requirements of your question.

declare @intvalue int
set @intvalue=5

declare @vsresult varchar(64)
declare @inti int
select @inti = 64, @vsresult = ''
while @inti>0
  begin
    select @vsresult=convert(char(1), @intvalue % 2)+@vsresult
    select @intvalue = convert(int, (@intvalue / 2)), @inti=@inti-1
  end
select @vsresult

这篇关于SQL Server 将整数转换为二进制字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆