OR 2字符串0,1的最佳方法

mjy*_*ani 6 sql-server bit

我有2个字符串,只包含0和1.我想要一个按字符串的结果字符串,或者按字符逐个字符.

DECLARE @str1 nvarchar;
DECLARE @str2 nvarchar; 
SET @str1= '11001100';
SET @str2= '00100110';

-- I want result to be : 11101110
Run Code Online (Sandbox Code Playgroud)

字符串的大小是可变的.我可以逐个使用for循环和OR字符.但是字符串的数量是可变的,它们的大小可能超过100万......有没有比FOR循环更好的方法?

Mar*_*ith 4

理想情况下,您会将其编码为二进制。

11001100是一个字节0xCC

存储为varchar意味着需要 8 个字节,声明为nvarchar需要 16 个字节。

然后您还可以使用 CLR 和按位运算符。

尽管使用 CLR 函数回答您提出的问题可能仍然是迄今为止性能最佳的方法。

using System;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;

public partial class UserDefinedFunctions
{
    [SqlFunction]
    public static SqlString StringOr(SqlChars a, SqlChars b)
    {
        if (a.Length != b.Length)
        {
            throw new Exception("Strings should be the same length.");
        }

        char[] c = new char[a.Length];

        for(int i =0; i < a.Length; i++)
        {
            c[i] = (a[i] == '0' && b[i] == '0' ? '0' : '1');
        }

        return (SqlString)(new SqlChars(c));        
    }
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述