日期:2014-05-19  浏览次数:20512 次

请问SQLServer2000中怎么把二进制的字段以字符串形式Select出来?
有一个Table,某个字段为二进制形式(binary),在查询管理器中Select出来就是形如”0x0A1F8697FF0000000000”,问题是存储过程不能返回二进制字段,不知道有什么办法可以Select出来变为“0A1F8697FF00”这样一个字符串呢?(我设计的这个字段以FF00为结束,FF00后面的字符忽略。

------解决方案--------------------
select cast(字段 as varchar(8000)) from [Table]
------解决方案--------------------
select cast(left(0x0A1F8697FF0000000000,charindex(0xFF00,0x0A1F8697FF0000000000)) as varbinary(8000)) as str


/*
str
------------------
0x0A1F8697FF00
*/
------解决方案--------------------
厉害,这回可以了
CREATE TABLE TEST6(A binary(50)) --DROP TABLE TEST6
INSERT TEST6 SELECT 0x0A1F8697FF0000000000
select cast(left(A,charindex(0xFF00,A)) as varbinary(8000)) as str from test6

0x0A1F8697FF00

------解决方案--------------------
???
INSERT TEST6 SELECT 0xAAAA1F8697FF00000000
select cast(left(A,charindex(0xFF00,A)) as varbinary(8000)) as str from test6
0x0A1F8697FF00
0xAAAA1F8697FF0000
------解决方案--------------------
declare @TEST6 binary(50)
set @TEST6= '0x0A1F8697FF0000000000 '
select cast(left(@TEST6,charindex( '0xFF00 ',@TEST6)) as varbinary(8000))

为什么这样查不到呢?
------解决方案--------------------
declare @bin varbinary(1000)
declare @result varchar(1000)
set @bin = 0x0A1F8697FF0000000000
EXEC master.dbo.xp_varbintohexstr @bin, @result output
----去掉字符串前面的 '0x '字符
set @result = stuff(@result,1,2, ' ')
----去掉最后的FF00后面的字符(当有多个FF00时只从最后一个FF00截取)
select reverse(substring(reverse(@result),charindex(reverse( 'FF00 '),reverse(@result)),len(@result)- charindex(reverse( 'FF00 '),reverse(@result))+1))

/*结果
0A1F8697FF00
*/
------解决方案--------------------
--try
CREATE PROC prc(@binvalue varbinary(6))
AS
BEGIN
SET NOCOUNT ON
DECLARE @charvalue varchar(20)
DECLARE @hexstring char(16)
DECLARE @i int
DECLARE @length int
SELECT @charvalue = ' '
SELECT @hexstring = '0123456789ABCDEF '
SELECT @i=1
SELECT @length=DATALENGTH(@binvalue)
WHILE (@i <= @length)
BEGIN
DECLARE @tempint int
DECLARE @firstint int
DECLARE @secondint int
SELECT @tempint = CONVERT(int, SUBSTRING(@binvalue,@i,1))
SELECT @firstint = FLOOR(@tempint/16)
SELECT @secondint = @tempint - (@firstint*16)
SELECT @charvalue = @charvalue +
SUBSTRING(@hexstring, @firstint+1, 1) +
SUBSTRING(@hexstring, @secondint+1, 1)
SELECT @i = @i + 1
END
select RTRIM(@charvalue)
END
GO

exec dbo.prc 0x0A1F8697FF0000000000

drop proc prc

--0A1F8697FF00