I have SQL datatable StudetnMaster having FirstName nvarchar(100) and contains Data Entry Gujarati Language (Unicode Chracters)
Sample:
StudentId FirstName
1 ઘનશ્યામ
2 જીગર
Now I have following query for searching:
Select *
from StudetnMaster
where FirstName like N'" + textBox1.Text.Trim() + "%'
It's working fine but in stored procedure I have to pass parameter for FirstName as Follows:
ALTER PROCEDURE dbo.StoredProcedure1
#FirstName nvarchar(100)
AS
select *
from StudentNew
where FirstName like N#FirstName+'%'
But it throws an Error saying :
Invalid Column Name N#FirstName
How can I use 'N' in SP for parameter because without using N' Unicode Text is not searchable?
For inline query as mentioned above i got result, but for stored procedure I got error, so how can we use 'N' in SP?
Is there any other solution for searching unicode characters in SP?
Thanks
Just like in comment was written- you dont have to add N to parameter.
As you define parameter as nvarchar, it means- 2 bytes per symbol (that what N stands for, when you write N'string').
If that necessary, you can add collation there:
select * from StudentNew
where FirstName like #FirstName+'%' Collate YourCollationName
Related
I'm dealing with some language issues in my SQL Server version 12.0.1800.
I have a table Persons and a stored procedure to return all persons based upon a like condition on their names. Name column is of type NVARCHAR(50).
The procedure works fine with the english languages, however when executing it with cyrillic characters, I need to use an N in front for results.
Does not work:
exec GET_PERSONS #argName = 'тест'
Works:
exec GET_PERSONS #argName = N'тест'
Problem is that I use this procedure from a C# client with entity framework 6. and there is no way to put an N in front of a parameter what I know, and according to sources I shouldn't need to if columns are nvarchar.
Call to procedure (returns nothing):
string name = "тест";
db.SP_GetPersons(name);
Procedure:
ALTER PROCEDURE [dbo].[GET_PERSONS]
#argName NVarchar(100)
AS
BEGIN
SELECT
name
FROM
Persons
WHERE
Name like ISNULL(#argName + '%', '%')
or Name like concat('% ', #argName, '%')
END
I am using below table structure, I want to create a view which will show a FirstName of ReportsTo field shown below.
Please let me give a suggestion how to create that view which will display all the reports to 's first name with (',') comma separator.
You join a table to itself just like any other join. The main this is to make sure both tables are aliased with differnt aliases
Your problem is that you have a one to many relationship stored in the table which is a huge design mistake. For the future, remember that anytime you think about storing information a comma delimted list, then you are doing it wrong and need a related table instead. So first you have to split the data out into the related table you should have had instead with two columns, EmplCode and ReportsTo (with only one value in reports to), then you can do the join just like any other join. We use a function that you can get by searching around the internet called fn_split to split out such tables when we get this type of infomation in client files.
If you search out fn_split, then this is how you can apply it:
Create table #UnsplitData (EmpCode varchar (10), ReportsTo varchar(20), FirstName varchar (10))
insert into #UnsplitData
values ('emp_0101', 'emp_0102,emp_0103', 'John')
, ('emp_0102', 'emp_0103', 'Sally')
, ('emp_0103', Null, 'Steve')
select *, employee.FirstName + ', ' + Reports.FirstName
from #UnsplitData Employee
join
(
select t.EmpCode , split.value as Reportsto, ReportName.Firstname
from #UnsplitData t
cross apply dbo.fn_Split( ReportsTo, ',') split
join #UnsplitData ReportName
on ReportName.EmpCode = split.value
) Reports
On Employee.EmpCode = Reports.empcode
From what I gather, I think you're trying to get the Firstname column and the ReportsTo column separated by a comma:
SELECT FirstName + ', ' + ReportsTo
FROM table
Edit: judging from the comments he's trying to do something else? Can someone rephrase for me?
SELECT E.*,
R.FirstName
FROM Employees E
JOIN Employees R
ON E.ReportsTo LIKE '%' + R.EmpCode + '%'
I have a code like below which calls to a SQL Server stored procedure
First name will be passed a value like 电子邮箱
sCmd.Parameters.Add("#FName", SqlDbType.NVarChar);
sCmd.Parameters.Add("#LName", SqlDbType.NVarChar);
sCmd.Parameters["#FName"].Value = firstname;
sCmd.Parameters["#LName"].Value = lastname;
In stored procedure:
#FName nvarchar(200),
#LName nvarchar(200)
INSERT INTO [dbo].[testunicode]
([col1]
,[col2])
VALUES
(#FName
,#LName);
But data is inserted as ???? even the table columns are NVarchar(max);
I tried with adding 'N' before passing to stored procedure, and also the below. But still the same. What is the best way of doing so?
Encoding tc = Encoding.GetEncoding("BIG5");
byte[] bytes = tc.GetBytes(firstname);
firstname = Encoding.Unicode.GetString(bytes)
I tried with adding 'N' before passing to Sp
no need because the .NET String supports Unicode and it will take care of Unicode. If you see the request that is passed on to the database you will notice that N' will be affixed automatically.
What is the best way of doing so.
You are doing it right. No need for passing in anything else.
But data is inserted as ????
Check the datatype in your table. Is it really NVarChar?
For example, the users of our app want to search products by entering a keyword of productName.
The Products table of the sql server database contains about 10 million records.
Are there any better and higher-performance search methods to implement instead of productName.Contains("keyword") using asp.net C# ?
I'm using stored procedures now, but linq to sql or entity framework are also a possibility.
If you want better performance then you could look into a full text search. Note that this is currently not supported by LINQ to SQL but you can write the SQL in a stored procedure and call the stored procedure from your application. The accepted answer for this StackOverflow post recommends reading this article.
Well you could achieve this from the db side using a LIKE
LIKE (Transact-SQL)
Something like
DECLARE #Table TABLE(
Val VARCHAR(50)
)
INSERT INTO #Table SELECT 'asdf'
INSERT INTO #Table SELECT 'tada'
INSERT INTO #Table SELECT 'foo'
INSERT INTO #Table SELECT 'bar'
INSERT INTO #Table SELECT 'test'
INSERT INTO #Table SELECT 'test foo'
DECLARE #Lookup VARCHAR(50)
SELECT #Lookup = 'foo'
SELECT *
FROM #Table
WHERE Val LIKE '%' + #Lookup + '%'
You should never fetch more data from your database than you need. So it is best for you to restrict your rows inside the data layer (ie. your stored procedure). You can do this by only returning matching rows:
SELECT * FROM Products WHERE ProductName LIKE '%' + #keyword + '%'
Where #keyword is a parameter to your store procedure.
But be aware that performance using LIKE can be slow, since it must read the entire table. You can better performance more by matching products that starts with the keyword:
SELECT * FROM Products WHERE ProductName LIKE #keyword + '%'
Note I removed the '%' before #keyword. This enables SQL Server to use an index on the ProductName column to find the rows much quicker!
Fore further help, please post your stored procedure...
Might be overkill but check out lucene.net, I believe it is what stack overflow uses for its searching
I want to use a query as following, I am looking for exact information/link to escape strings
BookTitle is NVARCHAR(200)
SELECT * FROM Books WHERE BookTitle IN ('Mars and Venus', 'Stack''s Overflow \r\n')
Question:
Does only "'" needs to be escaped or even \r\n needs to be escaped as well? MySql .Net Provider exposes a method to escape string values, is there any such function in Sql Server .Net Provider?
I probably need C# equivalent escaping for string values.
I am aware of Parameterized Command, but in order to minimize my server to client communication, and my values in IN clause are in number from 20 to 50, it becomes too much network expensive to run SELECTs for each value of BookTitle in one call. Rather running single query and returning all results cascaded helps saving network resources.
SQL Server won't recognise the \r\n sequence, whether it's escaped or not.
You'll need to do something like this instead if you want to match the \r\n in BookTitle:
-- \r = CHAR(13)
-- \n = CHAR(10)
SELECT *
FROM Books
WHERE BookTitle IN ('Mars and Venus', 'Stack''s Overflow ' + CHAR(13) + CHAR(10))
There are more things that have to be escaped than just quotes or new line characters. What if there's a binary input (by hacker)? Better use PreparedStatement (in java) or any other equivalent in the target language. Java sample:
PreparedStatement ps = con.prepareStatement("SELECT * FROM Books WHERE BookTitle IN (?, ?)");
ps.setString(1, "Mars and Venus");
ps.setString(2, "Stack's Overflow
and
");
ResultSet rs = ps.executeQuery();
....
I've run into a similar problem, where I needed to have a IN in my select query, and the number of elements varied at run time.
I use a parameterized query in the form of a stored procedure and pass in a delimited string containing the list of things I'm looking for. The escaping is automatically handled by the system, no need to take extraordinary steps. Better not make it delimited by characters that will be found in the text you're searching (like commas). a vertical bar ("|") would probably work best in many cases.
By the way, make sure the CRLFs in your table are CHAR(13)+CHAR(10) because the opposite way around isn't \r\n and you wouldn't find it if Environment.NewLine was part of your search.
Here's a stored procedure using a quick and dirty parse resolving to a table that I have used:
CREATE PROCEDURE FindBooks
(
#list varchar(500)
)
AS
CREATE TABLE #parse_table (item varchar(500))
DECLARE #temp VARCHAR(500)
DECLARE #result VARCHAR(500)
DECLARE #str VARCHAR(500)
DECLARE #pos SMALLINT
SET #temp = RTRIM(LTRIM(#list))
SET #pos = 1
WHILE #pos > 0
BEGIN
SET #pos = CHARINDEX('|',#temp)
IF #pos > 0
BEGIN
SET #result = SUBSTRING(#temp,1,#pos - 1)
SET #temp = RTRIM(LTRIM(SUBSTRING(#temp,#pos+1,LEN(#temp) - #pos)))
INSERT INTO #parse_table
SELECT #result
END
ELSE
INSERT INTO #parse_table
SELECT #temp
END
SELECT * FROM Books WHERE Title in (select * from #parse_table)
Simply create your list of book titles as a simple string (containing whatever embedded apostrophes, CRLFs, and so on) and use a parameterized query. Of course, your stored proc can contain other things besides the delimited list.
You could use table value parameters to pass in the the values for your IN statement. If you are not using a new enough version of visual studio and/or sql server to have access to table value parameters, you can instead pass in one comma separated list as string parameter, and then parse the the parameter into a table. There are several methods to split strings into a temp table/table variable. You can google "split function in sql server" for several options.
Usually what I'd do for situations like this, is pass your information in as a parameter, but in XML, so you can do something like this:
DECLARE #iDoc INT
EXEC sp_xml_preparedocument #iDoc OUTPUT, #MyXml
SELECT
*
FROM
MyTable
WHERE
MyColumn IN (SELECT [Id] FROM OPENXML(#iDoc,'/ss/s',2) WITH ([Id] INT '.'))
EXEC sp_xml_removedocument #iDoc
in this case, the xml would look like '<ss><s>1</s><s>2</s>...etc...</ss>'