I have 2 string that just contains 0 and 1. I want a result string that bitwise OR them charcter by character.
DECLARE @str1 nvarchar;
DECLARE @str2 nvarchar;
SET @str1= '11001100';
SET @str2= '00100110';
-- I want result to be : 11101110
The size of string is variable. I can use a for loop and OR the characters one by one. but the number of strings is variable and the size of them may be more than 1 million... Is there any better way than FOR
loop?
String indexing in Python is zero-based: the first character in the string has index 0 , the next has index 1 , and so on. The index of the last character will be the length of the string minus one.
The beginning character of a string corresponds to index 0 and the last character corresponds to the index (length of string)-1 . The length of a string is the number of characters it contains, including spaces, punctuation, and control characters.
If you leave slots empty, there's a default. [:] means: The whole thing. [::1] means: Start at the beginning, end when it ends, walk in steps of 1 (which is the default, so you don't even need to write it). [::-1] means: Start at the end (the minus does that for you), end when nothing's left and walk backwards by 1.
Ideally you would be encoding this as binary.
11001100
is a single byte 0xCC
.
Storing as varchar
means it takes 8 bytes and declared as nvarchar
it takes 16 bytes.
You could then also use CLR and bitwise operators.
Answering the question you asked though using a CLR function would likely still be by far the best performing way.
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));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With