How to pass large string_replacement in SQL Replace function - sql

I am attempting to replace a very large characters with a existing character in SQL, like the below
select REPLACE('main context', 'text', 'CharactersOver8000')
It would throw the following error
String or binary data would be truncated.
I try to cast the whole replace to nvarchar(max) but it does not work. Any suggestion? Currently its on SQL2012

What is the cause of this error message?
From the Docs Online
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.
What is the solution?
string_expression in your case is 'MainContext', so you need to cast it to VARCHAR(MAX) or NVARCHAR(MAX) datatypes as
select REPLACE(CAST('main context' AS VARCHAR(MAX), 'text', 'CharactersOver8000')

Casting inside the replace should work. I just tested this:
SELECT REPLACE(CAST('MainContext' AS varchar(max)), 'text', '{8005 character string}')
And it worked.

Related

[Insert Destination [26]] Error: Column "GovtProgYN" cannot convert between unicode and non-unicode string data types

I am executing an ETL process and getting captioned error:
source datatype is char(1) and destination datatype is nchar(2)
How do I insert data from char to nchar?
Please help.
You don't say what platform you are using but you need to tell it to convert. Something like
SELECT CAST(GOVTPROGYN as NCHAR(2)) FROM TABLENAME_YOU_DID_NOT_SAY
or
SELECT CAST(GOVTPROGYN as CHAR(1)) FROM TABLENAME_YOU_DID_NOT_SAY
Per your title error, the n in nchar adds support for unicode, (same with nvarchar vs varchar). The data you are trying to insert is type char, but your destination field (GovtProgYN?) requires nchar.
Most SQL engines support a CAST function, which looks something like this: CAST( field AS datatype ). In your case, you would want to cast your insert value to nchar(2).
Example:
INSERT INTO Table ( GovtProgYN )
VALUES ( CAST ( #value AS nchar(2) )
Some SQL engines, like SQL Server, require you to designate unicode using the N prefix to a character string. If you are trying to manually insert a nchar value, use N'c' rather than 'c'.
Example:
INSERT INTO Table ( GovtProgYN )
VALUES ( N'c' )

LIKE operator, N and % SQL Server doesn't work on nvarchar column

Is there any way to make following query Work?
declare #t nvarchar(20)
set #t='حس'
SELECT [perno] ,[pName]
FROM [dbo].[People]
Where [pName] like N''+#t +'%'
I cann't use like this:
Where [pName] like N'حس%'
Or using an stored procedure :
ALTER PROCEDURE [dbo].[aTest]
(#t nvarchar(20))
AS
BEGIN
SELECT [perno] ,[pName]
FROM [dbo].[People]
WHERE ([People].[pName] LIKE N'' +#t + '%')
END
You don't need to use N prefix in the WHERE clause since your variable is already nvarchar, and you are passing a variable not a literal string.
Here is an example:
CREATE TABLE People
(
ID INT,
Name NVARCHAR(45)
);
INSERT INTO People VALUES
(1, N'حسام'),
(2, N'حسان'),
(3, N'حليم');
DECLARE #Name NVARCHAR(45) = N'حس';--You need to use N prefix when you pass the string literal
SELECT *
FROM People
WHERE Name LIKE #Name + '%'; --You can use it here when you pass string literal, but since you are passing a variable, you don't need N here
Live demo
You may have seen Transact-SQL code that passes strings around using an N prefix. This denotes that the subsequent string is in Unicode (the N actually stands for National language character set). Which means that you are passing an NCHAR, NVARCHAR or NTEXT value, as opposed to CHAR, VARCHAR or TEXT.
From docs
Prefix Unicode character string constants with the letter N. Without the N prefix, the string is converted to the default code page of the database. This default code page may not recognize certain characters.
To answer your question in the comment with a simple answer, you are using the wrong datatype, so ALTER the stored procedure and change the datatype of your parameter from VARCHAR to NVARCHAR.
UPDATE:
Since you are using an SP, you can create your SP (according to your comment) as
CREATE PROCEDURE MyProc
(
#Var NVARCHAR(45)
)
AS
BEGIN
SELECT *
FROM People
WHERE Name LIKE ISNULL(#Var, Name) + '%';
--Using ISNULL() will return all rows if you pass NULL to the stored procedure
END
and call it as
EXEC MyProc N'حس'; --If you don't use N prefix then you are pass a varchar string
If you see, you need to use the N prefix when you pass literal string to your SP not inside the SP or the WHERE clause neither.
Demo for the SP
in these lines
declare #t nvarchar(20)
set #t='حس'
the 'حس' is a varchar constant that you then assign to an nvarchar variable. But you already lost data with the original conversion to that varchar constant and you cannot get that back.
The solution is to use an nvarchar constant:
set #t=N'حس'
It might be much simpler:
Try this
declare #t nvarchar(20)
set #t='حس';
SELECT #t; --the result is "??"
You are declaring the variable as NVARCHAR correctly. But the literal does not know its target. Without the N it is taken as a VARCHAR with the default collation.
The following line
Where [pName] like N''+#t +'%'
will search for a pName LIKE '??%'.
The solution should be
set #t=N'حس'; --<-- N-prefix

How to cast varchar in varbinary?

I try to update column value by appending varchar strings.
MyTable{
Id int,
MyValueColumn varbinary(max),
MyParamColumn varchar(50)
}
how i append:
'{"ZoneId":'+cast ([MyValueColumn] as varchar)+', "ZoneName":"'+[MyParamColumn]+'"}'
And this return correct value:
'{"ZoneId":1018, "ZoneName":"szz"}'
But now i cast result in varbinary and cast it again in varchar (for check varbinary correcy):
cast (cast('{"ZoneId":'+cast ([MyValueColumn] as varchar)+', "ZoneName":"'+[MyParamColumn]+'"}' as varbinary) as varchar)
and result:
'{"ZoneId":1018
Whats can be wrong?
When you are using cast to varbinary without explicit specification of length default length is 30.
So some trimming of your data can occurs if you're using varbinary, not varbinary(n) or varbinary(max) explicitly.
See MSDN for reference.
NOTE:
Also you have missed ' in your query: cast (cast({"ZoneId":' should be cast (cast('{"ZoneId":'
Update
I've created simple example:
declare #text varchar(50)
select #text = '{"ZoneId":'+cast (1018 as varchar)+', "ZoneName":"'+'szz'+'"}'
select cast(cast(#text as varbinary) as varchar)
select cast(cast(#text as varbinary(max)) as varchar(max))
it gives you trimmed text in first cast and original untrimmed text when we're using varbinary(max)

SQL Server implicit casting to VARCHAR(MAX)

I have a SQL function with following signature
(
#value as VARCHAR(MAX)
)
RETURNS NCHAR(47)
What will happen if the input of the function will be int?
Implicit casting to VARCHAR(MAX)?
i.e if the input is int 12 how will it be transferred to the function input leading zeros and 12 - "000000..000012"
It gets cast to varchar but there will be no leading 0's, it will simply be read as 12. Just because you specify varchar(max) doesn't mean it will use the space it has and automatically fill it with 0's.

Convert nvarchar(max) to varbinary(max)

Have table with values
report nvarchar(max) not null
description nvarchar(max)
In stored procedure I want select values from table and then convert it to varbinary max. I seletct :
select
CONVERT(varbinary(max), [report]) as [report],
ISNULL(CONVERT(varbinary(max), [description]), '') as [description]
from myTbl
but I get an error:
Implicit conversion from data type varchar to varbinary(max) is not allowed. Use the CONVERT function to run this query.
Please help me to solve this problem
The failure is occurring because you convert description to varbinary, but then try to cast any null values back to a varchar. You just need to move ISNULL inside the CONVERT or change the conversion value when null to a binary value.
ISNULL in CONVERT
SELECT
CONVERT(varbinary(MAX), report),
CONVERT(varbinary(max), ISNULL([description], '')) as [description]
FROM myTbl
Proper ISNULL Value
SELECT
CONVERT(varbinary(MAX), report),
ISNULL(CONVERT(varbinary(max), [description]), 0x) as [description]
FROM myTbl
Both versions will produce the same output 0x if description is null.