How to use parameters in contains method in store procedure - sql

I am testing contains method in store procedure. I would like to see data result like:
Example Result for John:
John Nick
Papa John
Harly John Fredy
I don't want to use LIKE method. Can we use starts with or ends with (*) operator with parameters in SP?
CONTAINS(name,#name) // query is working
but if i can try like this:
CONTAINS(name, '"john" OR "john*"') // query is working
CONTAINS(name,'"#name" OR "#name*"') // query is not working
With parameters same query is not working in SP. Is it posibble to do this in SP?
Thanks,

With CONTAINS, in order to pass a wildcard through with a variable, you need to make the wildcard a part of the variable.
The easiest way to do it within a stored procedure is adding a variable (or modifying your current variable).
For example,
DECLARE #nameX NVARCHAR(4000) = '"' + #name + '" OR "' + #name + '*"'
...
CONTAINS(name, #nameX)

Related

Using Like '%#mail%' in stored procedure

If I try to call a stored procedure to check for mail addresses containing a #mail it fails because it sees the #mail as a variable instead of a string literal
Is this what you want?
where email like '%' || #mail || '%'
|| here is the standard operator for string concatenation. This can very depending on the database.
You can use
Concat function
SELECT * FROM TableA WHERE Email LIKE CONCAT('%',#Email,'%')
I ended up creating a variable which holds the like #domainname placed it in the exec statement and it started working. So I guess the variable gets parced, the value is added to the query and its accepted as text in stead of searching for a variable

Like function in parameter stored procedure

Good day
I have problem with my store procedure as follow:
I need to know wchich manager have which employee
My statement with function WITH as SELECT working fine ,but
my problem is with procedure when iam caling back Iam geting 0 rows back.
I think should by problem with Function LIKE when Iam creating procerure.
Thank you for opinions
create procedure test #Name varchar(200) as
WITH n(Surname,Name) AS
(SELECT Surname,Name
FROM [dbo].[phonebook]
WHERE Name like '%#Name' --I need to be like here beause before name is XT245*/ SUBCODE
UNION ALL
SELECT subs.Surname, subs.Name
FROM [dbo].[phonebook] as subs, n
WHERE n.Surname = subs.Boss)
SELECT Name FROM n
exec test 'XX37485*/John'
This expression:
WHERE Name like '%#Name' --I need to be like here because before name is XT245*/ SUBCODE
is looking for names that have exactly that pattern of characters . . . # N a m e. There is no variable substitution.
If you want to use like, then:
WHERE Name like '%' + #Name
Note that this requires that the pattern end with #Name, so it will not match #Name anywhere in the string.

Appending character to variable in execute query

I want to execute a dynamic SQL statement, which searches for names whose last name is always a constant and first name is a variable.
Here is a query I have written for selecting a row with name='Test lastname'.
EXECUTE 'SELECT name FROM users
WHERE name=$1 lastname'
USING ('Test');
This generates a syntax error. Is it possible to do this?
I think you need something like this:
EXECUTE 'SELECT user_id FROM users
WHERE name=$1'
USING Test||' lastname' ;
Here Test is variable and 'lastname' is hard coded value
Also another way is as #JorgeCampos mentioned:
...WHERE name=$1 || '' lastname''' USING 'Test';

T-SQL: Cannot pass concatenated string as argument to stored procedure

Scenario:
Need to pass n arguments to a stored procedure. One of the arguments is of type varchar(x). That varchar argument needs to be constructed from a handful of other varchar variables. This problem uses SQL Server 2005, but this behaviour applies to all versions of SQL Server.
Setup:
DECLARE #MyString varchar(500), #MyBar varchar(10), #MyFoo varchar(10)
SELECT #MyBar= 'baz '
SELECT #MyFoo= 'bat '
-- try calling this stored procedure!
EXEC DoSomeWork #MsgID, 'Hello ' + #MyBar + '" world! "' + #MyFoo + '".'
This produces the exception in SQL Server: Incorrect syntax near '+'. Typically you might think that the datatype would be wrong (i.e. the variables are of different types, but that would produce a different error message).
Here's a correct implementation that compiles without error:
SELECT #MyString= 'Hello ' + #MyBar + '" world! "' + #MyFoo + '".';
EXEC DoSomeWork #ID, #MyString
Question: Why is it that T-SQL can't handle the concatenation of a varchar as an argument? It knows the types, as they were declared properly as varchar.
The EXECUTE statement simply has a different grammar then other statements like SELECT and SET. For instance, observe the syntax section at the top of the following two pages.
EXECUTE statement: http://msdn.microsoft.com/en-us/library/ms188332.aspx
SET statement: http://msdn.microsoft.com/en-us/library/ms189484.aspx
The syntax for EXECUTE only accepts a value
[[#parameter =] {value | #variable
[OUTPUT] | [DEFAULT]]
Whereas the syntax for SET accepts an expression
{#local_variable = expression}
A value is basically just a hard coded constant, but an expression is going to be evaluated. It's like having the varchar 'SELECT 1 + 1'. It's just a varchar value right now. However, you can evaluate the string like this:
EXEC('SELECT 1 + 1')
I suppose all I'm pointing out is that the EXEC command doesn't allow expressions by definition, which you apparently found out already. I don't know what the intention of the developers of T-SQL where when they made it that way. I suppose the grammar would just get out of hand if you where allowed to throw subqueries within subqueries in the parameter list of a stored procedure.
T-SQL Expression: http://msdn.microsoft.com/en-us/library/ms190286.aspx
You cannot do something like this either
exec SomeProc getdate()
you have to put all that stuff in a param like you are doing at your bottom query
It might be because it is non deterministic (at least for functions)
It's a limitation on the EXEC statement. See The curse and blessings of dynamic SQL for more information.

Dynamic SQL - Search Query - Variable Number of Keywords

We are trying to update our classic asp search engine to protect it from SQL injection. We have a VB 6 function which builds a query dynamically by concatenating a query together based on the various search parameters. We have converted this to a stored procedure using dynamic sql for all parameters except for the keywords.
The problem with keywords is that there are a variable number words supplied by the user and we want to search several columns for each keyword. Since we cannot create a separate parameter for each keyword, how can we build a safe query?
Example:
#CustomerId AS INT
#Keywords AS NVARCHAR(MAX)
#sql = 'SELECT event_name FROM calendar WHERE customer_id = #CustomerId '
--(loop through each keyword passed in and concatenate)
#sql = #sql + 'AND (event_name LIKE ''%' + #Keywords + '%'' OR event_details LIKE ''%' + #Keywords + '%'')'
EXEC sp_executesql #sql N'#CustomerId INT, #CustomerId = #CustomerId
What is the best way to handle this and maintaining protection from SQL injection?
You may not like to hear this, but it might be better for you to go back to dynamically constructing your SQL query in code before issuing against the database. If you use parameter placeholders in the SQL string you get the protection against SQL injection attacks.
Example:
string sql = "SELECT Name, Title FROM Staff WHERE UserName=#UserId";
using (SqlCommand cmd = new SqlCommand(sql))
{
cmd.Parameters.Add("#UserId", SqlType.VarChar).Value = "smithj";
You can build the SQL string depending on the set of columns you need to query and then add the parameter values once the string is complete. This is a bit of a pain to do, but I think it is much easier than having really complicated TSQL which unpicks lots of possible permutations of possible inputs.
You have 3 options here.
Use a function that converts lists tables and join into it. So you will have something like this.
SELECT *
FROM calendar c
JOIN dbo.fnListToTable(#Keywords) k
ON c.keyword = k.keyword
Have a fixed set of params, and only allow the maximum of N keywords to be searched on
CREATE PROC spTest
#Keyword1 varchar(100),
#Keyword2 varchar(100),
....
Write an escaping string function in TSQL and escape your keywords.
Unless you need it, you could simply strip out any character that's not in [a-zA-Z ] - most of those things won't be in searches and you should not be able to be injected that way, nor do you have to worry about keywords or anything like that. If you allow quotes, however, you will need to be more careful.
Similar to sambo99's #1, you can insert the keywords into a temporary table or table variable and join to it (even using wildcards) without danger of injection:
This isn't really dynamic:
SELECT DISTINCT event_name
FROM calendar
INNER JOIN #keywords
ON event_name LIKE '%' + #keywords.keyword + '%'
OR event_description LIKE '%' + #keywords.keyword + '%'
You can actually generate an SP with a large number of parameters instead of coding it by hand (set the defaults to '' or NULL depending on your preference in coding your searches). If you found you needed more parameters, it would be simple to increase the number of parameters it generated.
You can move the search to a full-text index outside the database like Lucene and then use the Lucene results to pull the matching database rows.
You can try this:
SELECT * FROM [tablename] WHERE LIKE % +keyword%