创建一个零的二进制字符串,其长度可变

时间:2013-02-22 23:44:54

标签: sql-server sql-server-2008 tsql

如果在运行时指定了长度(例如,在存储过程中),那么创建类型为varbinary(max)的二进制零字符串的最优雅方法是什么?

我可以使用REPLICATE函数来完成它,但这涉及大量的转换:

CAST(REPLICATE(CAST(CAST(0 AS tinyint) AS varbinary(max)), @size)
    AS varbinary(max))

(它甚至不适合......)有没有更好的方法呢?

编辑:代码适用于@size > 8000

3 个答案:

答案 0 :(得分:1)

原始表格

CAST(REPLICATE(CAST(CAST(0 AS tinyint) AS varbinary(max)), @size)
    AS varbinary(max))

仍然最适合我的需要。

答案 1 :(得分:0)

更好还是更短? :)

declare @size int
set @size = 3


select  CAST(REPLICATE(CAST(CAST(0 AS tinyint) AS varbinary(max)), @size) AS varbinary(max)),
        cast(replace(space(@size), ' ', 0x0) as varbinary(max))

答案 2 :(得分:0)

; with Foo as (
  select 1 as Size
  union all
  select Size * 2
    from Foo
    where Size < 65536 )
  select Size, Cast( Replicate( Char( 0 ), Size ) as VarBinary(MAX) ) as WideZero
    from Foo
    option ( maxrecursion 0 )