我在SQL Server的varchar(max)列中有值0x4D79205465737420537472696E67
。我想将其转换为二进制值0x4D79205465737420537472696E67
并检索第0个字节的前3位。
任何帮助都将不胜感激,谢谢。
答案 0 :(得分:0)
DECLARE @x varchar(max) = '0x4D79205465737420537472696E67'
SELECT CONVERT(binary(1), LEFT(@x,4), 1) / 32
答案 1 :(得分:0)
看看这是否适合您:
IF NOT EXISTS ( SELECT 1
FROM sys.objects
WHERE name = 'NthBit'
AND type = 'FN' )
BEGIN
--DROP FUNCTION dbo.NthBit;
EXEC( 'CREATE FUNCTION dbo.NthBit() RETURNS INTEGER AS BEGIN RETURN 1; END' );
END;
GO
ALTER FUNCTION dbo.NthBit
(
@StringRep VARCHAR( MAX ),
@ByteNumber INTEGER = 0,
@BitNumber INTEGER = 0
) RETURNS BIT AS BEGIN
/*
Returns the nth bit of the binary representation of @StringRep,
enumerated naively ( 01234567 rather than 76543210 )
*/
RETURN POWER( 2, 7 - @BitNumber )
& ( SUBSTRING( CONVERT( VARBINARY( MAX ), @StringRep, 1 ), @ByteNumber + 1, 1 ) );
END;
GO
DECLARE @Binary VARCHAR( MAX );
SET @Binary = '0x4D79205465737420537472696E67';
SELECT [1st] = dbo.NthBit( @Binary, 0, 0 ), -- Sign bit, in this case
[2nd] = dbo.NthBit( @Binary, 0, 1 ),
[3rd] = dbo.NthBit( @Binary, 0, 2 ),
[4th] = dbo.NthBit( @Binary, 0, 3 ),
[5th] = dbo.NthBit( @Binary, 0, 4 ),
[6th] = dbo.NthBit( @Binary, 0, 5 ),
[7th] = dbo.NthBit( @Binary, 0, 6 ),
[8th] = dbo.NthBit( @Binary, 0, 7 );
GO