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

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');

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 : insert Arabic letter to database

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))

T-SQL Replace Multiple Values with Wildcards

I want to replace characters , and /. I can do this with:
DECLARE #OMG VARCHAR(200)
SET #OMG = 'ABC,DE/F'
SELECT REPLACE(REPLACE(#OMG,'/','|') ,',','|')
The second query does not work however. Is there just typo or the task cannot be achieved with this code? I wanted to use wildcard for set of characters that should be replaced.
SELECT REPLACE(#OMG,[,/],'|')
It returns:
Msg 207, Level 16, State 1, Line 7
Invalid column name ',/'.
You can define all the variables to be replaced and the replacement inside a table use it.
create TABLE #ReplaceStrings (symb VARCHAR(5),replace_char varchar(5))
INSERT INTO #ReplaceStrings
(symb,replace_char)
VALUES ('/','|'),(',','|')
DECLARE #OMG VARCHAR(200)
SET #OMG = 'ABC,DE/F'
SELECT #OMG = Replace(#OMG, symb, replace_char)
FROM #ReplaceStrings
select #OMG
Here in a single replace you can replace all the unwanted characters.
Update: to replace data from table
create TABLE ReplaceStrings (symb VARCHAR(5),replace_char varchar(5))
create table #table (String varchar(500))
insert into #table values ('ABC,DE/F'),('AB,C,DE/F/')
INSERT INTO ReplaceStrings VALUES ('/','|'),(',','|')
Scalar Function
Create function replacechar(#Ip_String varchar(500))
returns varchar(500)
begin
SELECT #Ip_String=Replace(#Ip_String, symb, replace_char)
FROM ReplaceStrings
return #Ip_String
end
Execute the function
select String,dbo.replacechar(String) Replaced_String from #table

sql function in stored procedure

I have a scalar function for formatting the text into uppercase and remove leading, trailing spaces etc. During an insert operation in a stored procedure, I'm invoking the function like this:
insert into tablename(col1,col2) values ( dbo.function_name(value1),value2)
Here the col1 is NOT NULL. The above statement is throwing an error "Attempting to set a non-NULL-able column's value to NULL". But if you run the function alone, it return the value properly.
Please help explain where I'm going wrong.
insert into table(Col1,Col2)
values (isnull(dbo.function_name(value1),''),value2)
How about you try placing the value in a variable first and to help when you debug it.
DECLARE #val1 varchar(100)
SET #val1 = dbo.function_name(value1)
PRINT #val1 -- print it to see if we get what we expect.
SET #val1 = isnull(#val1,'') -- We can also check for null
insert into tablename(col1,col2) values ( #val1,value2)
This will at least confirm what is happening during execution and you can confirm the function is operating as you expect.
Could you add a short but complete example that actually demonstrates the problem to your question. The following does not produce any errors, but I'm having to guess in a lot of places:
create table tablename (
col1 varchar(20) not null,
col2 varchar(10) null
)
go
create function dbo.function_name (
#InVal varchar(20)
)
returns varchar(20)
as
begin
return UPPER(LTRIM(RTRIM(#InVal)))
end
go
create procedure dbo.procname
#value1 varchar(20),
#value2 varchar(10)
as
insert into tablename(col1,col2) values ( dbo.function_name(#value1),#value2)
go
exec dbo.procname ' abc ','def'
go
select * from tablename
Result:
col1 col2
ABC def

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();
}