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

2021-09-10 00:00:00 tsql sql-server-2008 sql-server

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

我可以使用 REPLICATE 函数来做到这一点,但这涉及大量的转换:

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

(它甚至不适合在线...)有没有更好的方法来做到这一点?

EDIT:代码应该适用于 @size >8000.

解决方案

原始表单

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

仍然最适合我的需求.

What is the most elegant way to create a string of binary zeros, of type varbinary(max), if the length is specified at run time (e.g., in a stored procedure)?

I could do it using the REPLICATE function, but this involves a lot of casting:

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

(It doesn't even fit on the line...) Is there a better way to do this?

EDIT: The code should work for @size > 8000.

解决方案

The original form

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

still suits my needs best.

相关文章