我正在使用的代码是:
DECLARE @var1 AS int;
SET @var1=8191;
WITH A AS (
SELECT 0 AS ORD, @var1 AS NUMBER, CAST('' AS VARCHAR(20)) AS BITS
UNION ALL
SELECT ORD+1, NUMBER/2, CAST(BITS+CAST(NUMBER%2 AS VARCHAR(20)) AS VARCHAR(20))
FROM A
WHERE NUMBER>0)
SELECT RIGHT('000000000000000'+ CASE WHEN BITS='' THEN '0' ELSE REVERSE(BITS) END,16) AS BIN_VALUE
FROM A
WHERE NUMBER=0
这得到存储在@ Var1中的数字的二进制值,所以对于8191,它会给出结果0001111111111111,我想捕获该数字,所以我可以在另一个查询中使用它,例如在@ Var2中。非常感谢任何帮助。
答案 0 :(得分:1)
这不适合你吗?
SELECT @var2 = RIGHT('000000000000000'+ CASE WHEN BITS='' THEN '0' ELSE REVERSE(BITS) END,16)
FROM A
WHERE NUMBER = 0;
答案 1 :(得分:1)
试试这个...我添加了Declare @Var2
,在最后的选择中我添加了SELECT @Var2 =
位。
DECLARE @Var2 AS VARCHAR(50) -- or whatever data type you need
DECLARE @var1 AS int;
SET @var1=8191;
WITH A AS (
SELECT 0 AS ORD, @var1 AS NUMBER, CAST('' AS VARCHAR(20)) AS BITS
UNION ALL
SELECT ORD+1, NUMBER/2, CAST(BITS+CAST(NUMBER%2 AS VARCHAR(20)) AS VARCHAR(20))
FROM A
WHERE NUMBER>0)
SELECT @Var2 = RIGHT('000000000000000'+ CASE WHEN BITS='' THEN '0' ELSE REVERSE(BITS) END,16) AS BIN_VALUE
FROM A
WHERE NUMBER=0
答案 2 :(得分:1)
没有递归CTE的另一种方式
DECLARE @var1 AS SMALLINT = 8191,
@Var2 CHAR(16);
SELECT @Var2 =
RIGHT('000000000000000'+
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
FORMAT(@var1,'x')
,'0','0000')
,'1','0001')
,'2','0010')
,'3','0011')
,'4','0100')
,'5','0101')
,'6','0110')
,'7','0111')
,'8','1000')
,'9','1001')
,'a','1010')
,'b','1011')
,'c','1100')
,'d','1101')
,'e','1110')
,'f','1111')
,16)
SELECT @Var2