SQL Server stored procedure convert varbinary to Base64String - sql

I have been tasked to create a stored procedure which can look at a table and pull up the ObjectGUID and extensionAttribute6 column and do a compare.
Basically the objectGUID is a varbinary column and extensionAttribute6 is a nvarchar column. What I really need to do is pull up all records where extensionAttribute6 is not null, then take the value of objectGUID and convert it to a base-64 string value and compare that value with value in the column extensionAttribute6 of that record. If the value match, then insert a calculated column called Compliance (nvarchar(10)) and put True there, else put false there.

You can use XML to get Base64:
Getting records that decoded(objectGUID) = extensionAttribute6
SELECT *
FROM your_tab
WHERE extensionAttribute6 IS NOT NULL
AND CAST(CAST('' as XML).value('xs:base64Binary(sql:column("objectGUID"))', 'VARBINARY(MAX)') AS NVARCHAR(MAX)) = extensionAttribute6
And update:
UPDATE your_tab
SET Compliance = IIF(CAST(CAST('' as XML).value('xs:base64Binary(sql:column("objectGUID"))', 'VARBINARY(MAX)') AS NVARCHAR(MAX)) = extensionAttribute6, 'True', 'False')
For storing True/False you should use BIT datatype instead of string.
EDIT:
SELECT *
[Compliance] = IIF(CAST(CAST('' as XML).value('xs:base64Binary(sql:column("objectGUID"))', 'VARBINARY(MAX)') AS NVARCHAR(MAX)) = extensionAttribute6, 'True', 'False')
FROM your_tab

Related

SQL Server : Nvarchar to Varchar

I have a table with two columns, one is of type Varchar and the other in NVarchar.
I want to update all the rows so VarcharField = NVarcharField.
It won't let me because some of the rows contain chars that are not allowed in varchar column with the current code page.
How can I find these rows?
Is it possible to remove any char that doesn't fit the specific code page I'm using?
SQL Server 2012.
You can find the rows by attempting to convert the nvarchar() col to varchar():
select nvarcharcol
from t
where try_convert(varchar(max), nvarcharcol) is null;
Try this..
to find the rows with values that are not supported by varchar
declare #strText nvarchar(max)
set #strText = 'Keep calm and say தமிழன்டா'
select cast(#strText as varchar(max)) col1 , N'Keep calm and say தமிழன்டா' col2
Here #strText has non-english chars, When you try to cast that into varchar the non-english chars turns into ????. So the col1 and col2 are not equal.
select nvar_col
from tabl_name
where nvar_col != cast(nvar_col as varchar(max))
Is it possible to remove any char that doesn't fit the specific code page I'm using?
update tabl_name
set nvar_col = replace(cast(nvar_col as varchar(max)),'?','')
where nvar_col != cast(nvar_col as varchar(max))
Replace ? with empty string and update them.
If Gordon's approach doesn't work because you get question marks from TRY_CONVERT instead of the expected NULL, try this approach:
SELECT IsConvertible = CASE WHEN NULLIF(REPLACE(TRY_CONVERT(varchar(max), N'人物'), '?',''), '') IS NULL
THEN 'No' ELSE 'Yes' END
If you need it as filter for the rows that can't be converted:
SELECT t.*
FROM dbo.TableName t
WHERE NULLIF(REPLACE(TRY_CONVERT(varchar(max), t.NVarcharField), '?',''), '') IS NULL

View Column length Changed,when created with case and replace

View column length (Postcode) has increased to varchar(8000)!, when created from the underlying table, it's column length is only varchar(8)
Database is SQL Server 2012.
create view v_testing as
select Postcode = CASE WHEN LEN(A.RealPostcode) = 0 THEN NULL
ELSE REPLACE(A.RealPostcode,' ','')
END,
A.RealPostcode
from dbo.Table A;
https://msdn.microsoft.com/en-us/library/ms186862.aspx
If string_expression is not of type varchar(max) or
nvarchar(max),REPLACE truncates the return value at 8,000 bytes. To
return values greater than 8,000 bytes, string_expression must be
explicitly cast to a large-value data type.
So just use cast function:
create view v_testing as
select Postcode = CASE WHEN LEN(A.RealPostcode) = 0 THEN NULL
ELSE CAST(REPLACE(A.RealPostcode,' ','') AS VARCHAR(8))
END,
A.RealPostcode
from dbo.Table A;

SQL Server compare varchar field with binary(16)

I have 2 tables - Table A with primary key column of type binary(16) and another table B with foreign key referring to the same column but with data type as varchar(50). So table A has values like 0x0007914BFFEC4603A6900045492EFA1A and table B has the same value stored as 0007914BFFEC4603A6900045492EFA1A.
How do i compare these 2 columns, which would give me
0007914BFFEC4603A6900045492EFA1A = 0x0007914BFFEC4603A6900045492EFA1A
You will need to convert the binary(16) to a string. A sample of how to do this can be found in the question below. This question converts a varbinary to a string, but the same technique can be used for a binary column or variable:
SQL Server converting varbinary to string
Example code for how to do this is below:
declare #bin binary(16), #str varchar(50)
set #bin = 0x0007914BFFEC4603A6900045492EFA1A
set #str = '0007914BFFEC4603A6900045492EFA1A'
select #bin as'binary(16)', #str as 'varchar(50)'
-- the binary value is not equal to the string value
-- this statement returns 'binary value is not equal to string'
if #bin = #str select 'binary value is equal to string'
else select 'binary value is not equal to string'
declare #binstr varchar(50)
select #binstr = convert(varchar(50), #bin, 2)
select #binstr
-- the converted string value matches the other string
-- the result of this statement is "converted string is equal"
if #binstr = #str select 'converted string is equal'
else select 'converted string is NOT equal'
To use this in a join, you can include the conversion in the ON clause of the inner join or in a WHERE clause:
select *
from TableA
inner join TableB
on TableB.char_fk = convert(varchar(50), TableA.bin_pk, 2)
UPDATE
For SQL Server 2005, you can use an XML approach shown by Peter Larsson here:
-- Prepare value
DECLARE #bin VARBINARY(MAX)
SET #bin = 0x5BAA61E4C9B93F3F0682250B6CF8331B7EE68FD8
-- Display the results
SELECT #bin AS OriginalValue,
CAST('' AS XML).value('xs:hexBinary(sql:variable("#bin"))', 'VARCHAR(MAX)') AS ConvertedString
You can also use the undocumented function sys.fn_varbintohexstr, but as this post on dba.stackexchange.com explains, there are several reasons why you should avoid it.
CONVERT with style 2 to get a binary representation of the hexadecimal string;
... where TableA.bin_pk = CONVERT(VARBINARY, TableB.char_fk, 2)
The correct aproach is to set both fields in the same datatype. in order to to do this create a new table say temp and use select into and convert:
select field1,...,convert(varchar(50),varbinary(16),fieldToConvert)...,fieldN
into myNewTable
Found the answer. I need to use
master.dbo.fn_varbintohexstr (#source)
which converts a varbinary to varchar, and then works perfectly well for comparison in my scenario.

Varchar to Number in sql

i have written a query in which i am fetching an amount which is a number like '50,000','80,000'.
select Price_amount
from per_prices
As these values contain ',' these are considered to be varchar.Requirement is to to print these as 'number' with ','
that is how can '50,000' be considered as number and not varchar
If a value has anything other than numbers in it, it is not an integer it is string containing characters. in your case you have a string containing character 5, 0 and ,.
If this is what is stored in your database and this is what you want to display then go ahead you do not need to change it to Integer or anything else. But if you are doing some calculations on these values before displaying them, Yes then you need to change them to an Integer values. do the calculation. Change them back to the varchar datatype to show , between thousands and hundred thousands and display/select them.
Example
DECLARE #TABLE TABLE (ID INT, VALUE VARCHAR(100))
INSERT INTO #TABLE VALUES
(1, '100,000'),(2, '200,000'),(3, '300,000'),(4, '400,000'),
(1, '100,000'),(2, '200,000'),(3, '300,000'),(4, '400,000')
SELECT ID, SUM(
CAST(
REPLACE(VALUE, ',','') --<-- Replace , with empty string
AS INT) --<-- Cast as INT
) AS Total --<-- Now SUM up Integer values
FROM #TABLE
GROUP BY ID
SQL Fiddle
you could combine the Replace and cast function
SELECT CAST(REPLACE(Price_amount, ',', '') AS int) AS Price_Number FROM per_prices
for more information visit 'replace', 'cast'
SQLFiddle

STORED PROCEDURE CONVERT ERROR

Have stored procedure where i want update data and want cast some varbinary to nvarchar
UPDATE [payterm].[dict_default_values]
SET [default_value] = CAST(#value AS NVARCHAR(MAX))
,[descr] = CAST(#descr AS NVARCHAR(MAX))
,[grp] = #grp
WHERE [code] = #code;
IF ##ROWCOUNT = 0
INSERT INTO [payterm].[dict_default_values]
([code], [default_value], [descr], [grp])
VALUES
(#code, #value, #descr, #grp);
When i put parametrs there were error : Implicit conversion from data type varchar to varbinary is not allowed. Use the CONVERT function to run this query
You also need to cast in the VALUES part of your INSERT statement.
Without knowing the data types of your variable/parameters/columns it's difficult to give a specific answer though.