SQL Server : insert Arabic letter to database - sql

First of all, this problem doesn't exist when the text is just English, but when I insert Arabic text, I got the problem.
Look at my code
CREATE PROCEDURE insertToPinTableCardActivation
(#callerID VARCHAR (200),
#vAccount VARCHAR (200))
AS
BEGIN
DECLARE #textEnglish NVARCHAR(1000) --missing length previously
SET #textEnglish = 'Dear customer, your Card linked to account number '+ #vAccount --missing set keyword
SET #textEnglish = #textEnglish + ' is now activated. Thank you for banking with us.'
SET #textEnglish = 'عزيزي الزبون، تم تفعيل بطاقة الصراف الآلي التابعة لحسابكم رقم ' + #vAccount
INSERT INTO pinData([CallerID], [body], [processed])
VALUES (#callerID, #textEnglish, 0)
END
The code creates a string of mix Arab and English, and then insert it to a table.
My problem is that look what it is being inserted to the table
even though i already made the field body as nvarchar
could you help please
Update 1
I am inserting from my sql server when executing the stored procedure
update 2
if i go to the table and insert the data manually in arab, the arab letters shows correctly

IF you want to insert Unicode string literals, you must prepend your string literal with an N prefix - try this:
SET #textEnglish = N'...(insert your Arabic text here)...'
Otherwise, your text is reverted back to a non-Unicode format before being stored - and that's why you lose the Arabic text....
And also: if you're concatenating with VARCHAR parameters, I'd recommend using an explicit CAST to NVARCHAR (include a length when casting!):
SET #textEnglish = N'Dear customer, your Card linked to account number ' + CAST(#vAccount AS NVARCHAR(100))

Related

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

SQL Server : can't concatenate string in the middle of other strings

In my SQL Server stored procedures I want to do this:
"hello xxx how are you"
where xxx is a value of a variable
I tried this
CREATE PROCEDURE insertToPinTable
(#callerID VARCHAR (200),
#vAccount VARCHAR (200))
AS
BEGIN
DECLARE #textEnglish VARCHAR
textEnglish = CONCAT ( "hello", #vAccount)
INSERT INTO pinData([CallerID], [body], [processed])
VALUES (#callerID, #textEnglish, 0)
END
I get an error
Incorrect syntax near 'textEnglish'
it seems that using CONCAT is not correct, could you help me please
(if I can insert the value of vAccount to the hello word, then in the same way I can insert the value of textEnglish, to the string how are you)
CREATE PROCEDURE insertToPinTable
(
#callerID VARCHAR (200),
#vAccount VARCHAR (200)
)
AS
BEGIN
DECLARE #textEnglish VARCHAR(255) --missing length previously
set #textEnglish = 'hello'+ #vAccount --missing set keyword
INSERT INTO pinData([CallerID], [body], [processed]) VALUES (#callerID, #textEnglish, 0)
END
If you just want to change a string from
"hello xxx how are you"
to
"hello Mr. Smith how are you"
You might think about place holder replacement:
Define your string as a template:
DECLARE #template VARCHAR(100)='hello {Name} how are you?';
And then use
SELECT REPLACE(#template,'{Name}','Mr. Smith');

Search a table using a string

I have a stored procedure which searches a table for a variable set by the user it works fine but the search only finds the first letter of the string input.
I'm using ->
ALTER PROCEDURE [dbo].[test]
#search_string varchar
AS
BEGIN
SET NOCOUNT ON;
IF (#search_string IS NOT NULL) OR (LEN(#search_string) > 0)
SELECT [archive_id]
[archive_id],
[display_name]
FROM [test1].[dbo].[ARCHIVE_id]
WHERE [display_name] like #search_string+'%';
What I am trying to figure out is how I can search for a whole word in the display_name column.
Any help would be appreciated.
Mark
You have to declare the size of the variable
ALTER PROCEDURE [dbo].[test]
#search_string varchar(50)
This should work
See LIKE
% Any string of zero or more characters.
_ Any single character.
[ ] Any single character within the specified range ([a-f]) or set ([abcdef]).
[^] Any single character not within the specified range ([^a-f]) or set ([^abcdef]).

sql put " inside "" when doing a bulk insert stored procedure

My procedure for bulk insert is below:
ALTER PROCEDURE [dbo].[usp_impt]
AS
BEGIN
Declare #SQL1 varchar(150), #path varchar(100),
#pathtable varchar(100), #date datetime
set #date = getdate()
-- set path for files
set #path= '\\ff\avc\ce\ed_imp\'
set #pathtable = #path + 'ABC20140723.csv'
-- Delete data from tables
delete from table1
-- set sql
set #SQL1 = "BULK INSERT dbo.table1 FROM '" + #pathtable
+ "' WITH (FIRSTROW = 3,MAXERRORS = 0,FIELDTERMINATOR = ',')"
-- Bulk insert
exec(#sql1)
end
It works fine except when my data has "Google,Inc", it is converted to "Google" "Inc".
I want to write FIELDTERMINATOR = '","' instead of ',', however, I don't know how to put it into my #sql1 string?
Also, is it recommended I write a format file? My csv file has 200 columns and rows. Do I need to write each row? Thanks for any advice.
Short answer is you can't do this with BULK INSERT as is. BULK INSERT can't tell what comma is a delimiter and what comma is part of the data. Your source data apparently doesn't have the string field values quoted (i.e. surrounded by quotes). For comma separated fields, if ANY of the data contains a comma, it must be surrounded by quotation marks or BULK INSERT will view it as a field terminator. You will have to update your source data to surround strings with quotation marks before inserting.
I ran into this frequently while running data loads from text files and csv files. The only solution was to get the source of the data to add quotes or to use a different delimiter, such as a pipe ( | ) or to switch to fixed width fields. In either case, the source data has to be fixed.

how to insert unicode text to SQL Server from query window

I'm using the following code:
INSERT INTO tForeignLanguage ([Name]) VALUES ('Араб')
this value inserted like this '????'
How do I insert unicode text from the sql management studio query window?
The following should work, N indicates a "Unicode constant string" in MSSQL:
INSERT INTO tForeignLanguage ([Name]) VALUES (N'Араб')
The perfect solution with data type limitation:
Basically in MS-SQL Server Amharic text not working properly when the column datatype is 'text'.Therefore to put Amharic text on column with datatype text, first change the text datatype to 'nvarchar(MAX)' or just 'nvarchar' with any char length that MS-SQL Server supported.
In my case, the task at hand was to update an SQL table which contains list of countries in two languages in which the local language (Amharic) column was null so executing the following works fine.
Update [tableName] set [columnName] = N'አሜሪካ'
The N in N'አሜሪካ' is the key to put the string as it is in your specific column.
Thanks to Ian's answer, you can directly run this code from query window:
declare #FamilyName nvarchar(40)
set #FamilyName = N'嗄嗄嗄'
insert into table(LoginName, Password) select #FamilyName as LoginName, 123 as Password
However, if you wish to perform the above insert through stored procedure, it's needed to attach N as prefix:
CREATE PROCEDURE Example
#FAMILY_NAME NVARCHAR(40)
AS
BEGIN
SET NOCOUNT ON;
declare #query nvarchar(400);
set #query ='insert into table(LoginName, Password) select N'''+ #FAMILY_NAME +''' as LoginName, 123 as Password';
EXECUTE sp_executesql #query;
END
Hope this helps..
Just make datatype NVarchar in database and following;
internal string InsertUpdate(classname obj)
{
SqlParameter[] sqlparam = new SqlParameter[];
sqlparam[] = new SqlParameter("#DESC1", SqlDbType.NVarChar);
sqlparam[].Value = NullHandler.String(obj.DESC1);
sqlparam[] = new SqlParameter("#DESC2", SqlDbType.NVarChar);
sqlparam[].Value = NullHandler.String(obj.DESC2);
obj.InsertUpdateTable("spname", "sp", sqlparam);
if (sqlparam[].Value != DBNull.Value)
return sqlparam[].Value.ToString();
}