Is concatenating parameters with wildcards safe in stored procs? - sql

Is concatenating parameter values with % in stored procedures safe from SQL injection?
I have a stored procedure that allows the user to do searches for records that contain the given value in the columns of a table:
CREATE PROC sp_Search
#SearchValue NVARCHAR(255)
AS
BEGIN
SELECT * FROM TableA WHERE ColumnA LIKE '%' + #SearchValue + '%' OR ColumnB LIKE '%' + #SearchValue + '%'
END

can you do ?
CHARINDEX(#SearchValue, [COLUMNA]) > 0
OR CHARINDEX(#SearchValue, [COLUMNB]) > 0

Related

How to use dynamic filter in sql procedure?

I want use Dynamic filter in sql Procedure
,like this
Select * from Table Where #Filter
Can I Write Like That Or Was Diffrent Ways to Use
I must Use this Syntax because I Want Remove Select in Application and Use Procedure.
CREATE PROCEDURE SP_DynamicFilter
(
-- Optional Filters for Dynamic Search
#COLUMN1 INT = NULL,
#COLUMN2 NVARCHAR(50) = NULL,
#COLUMN3 NVARCHAR(50) = NULL,
#COLUMN4 NVARCHAR(50) = NULL
)
AS
BEGIN
SELECT *
FROM TableName
WHERE
(#COLUMN1 IS NULL OR Column1 = #COLUMN1)
AND (#COLUMN2 IS NULL OR Column2 LIKE '%' + #COLUMN2 + '%')
AND (#COLUMN3 IS NULL OR Column3 LIKE '%' + #COLUMN3 + '%')
AND (#COLUMN4 IS NULL OR Column4 LIKE '%' + #COLUMN4 + '%')
END
CREATE PROCEDURE spProcedurName
#Filter datatype
AS
BEGIN
SELECT *
FROM Table
WHERE columnName= #Filter
END
You can paramater like that.
#Query='
Select * from table' + #Filter
exec #Query

SQL Server | storing output of select query to temp table using sp_MSforeachdb

I want to execute select query on all databases starting with 'ABC_%' if the filename consist of '?'.
Wrote the below query for this purpose but it results nothing:
DECLARE #result TABLE (o varchar(250), h uniqueidentifier, i uniqueidentifier, k nvarchar(250))
INSERT INTO #result
EXEC sp_MSforeachdb 'Begin
USE [?]
IF DB_NAME() like ''ABC_%''
BEGIN
SELECT DB_NAME() as DatabaseName
,[FileId]
,[HRDataId]
,[FileName]
FROM [?].[dbo].[UploadedFile]
where FileName like ''%?%''
END
End'
SELECT o
,h
,i
,k
from #result;
But I am aware that some databases have some '?' in fileName field. but the result is always blank.
Regards,
Anjani
It was because of the ? is treated as database name in sp_MSforeachdb stored procedure. I escape using ? using:
where FileName like ''%'' + CONVERT(VARCHAR(32), 0x3F) + ''%''

fast search specific column for specific keywords with stored procedure

I wrote a stored procedure that gets:
"SearchKeys" - keys to search separated by ',' "key1,key2"
"ToSearch" - Tables to search in separated by ',' with colums after ':' separated by '.' "table1:column1.column2,table2:column1.column2"
At the end procedure returns table with name of table and row id were the key was found.
here is the code:
--Search keys in tables
CREATE PROCEDURE [dbo].[Search_All]
(
#SearchKeys nvarchar(50), --Keys to search separated by ','
#ToSearch varchar(200) --Tables to search in separated by ',' with colums after ':' separated by '.'
)
AS
BEGIN
--create table with found values
CREATE TABLE #Results (TargetId int, DBName varchar(20))
--Split SearchKeys to Keys
WHILE LEN(#SearchKeys) > 0
BEGIN
DECLARE #Key NVARCHAR(25)
IF CHARINDEX(',',#SearchKeys) > 0
SET #Key = SUBSTRING(#SearchKeys,0,CHARINDEX(',',#SearchKeys))
ELSE
BEGIN
SET #Key = #SearchKeys
SET #SearchKeys = ''
END
--Split ToSearch to Tables
WHILE LEN(#ToSearch) > 0
BEGIN
DECLARE #TableAndColums VARCHAR(200)
IF CHARINDEX(',',#ToSearch) > 0
SET #TableAndColums = SUBSTRING(#ToSearch,0,CHARINDEX(',',#ToSearch))
ELSE
BEGIN
SET #TableAndColums = #ToSearch
SET #ToSearch = ''
END
SET #ToSearch = REPLACE(#ToSearch,#TableAndColums + ',' , '')
--Split #TableAndColums to Table and Colums
--Select Table
DECLARE #Table VARCHAR(25)
SET #Table = SUBSTRING(#TableAndColums,0,CHARINDEX(':',#TableAndColums))
SET #TableAndColums = REPLACE(#TableAndColums,#Table + ':' , '')
--Split to Colums
WHILE LEN(#TableAndColums) > 0
BEGIN
DECLARE #Column VARCHAR(25)
IF CHARINDEX('.',#TableAndColums) > 0
SET #Column = SUBSTRING(#TableAndColums,0,CHARINDEX('.',#TableAndColums))
ELSE
BEGIN
SET #Column = #TableAndColums
SET #TableAndColums = ''
END
BEGIN
--insert result in to #Results table
INSERT INTO #Results
EXEC
(
'SELECT ' + #Table + '.Id AS ''TargetId'', '''+#Table+''' AS ''DBName''
FROM ' + #Table +
' WHERE ' + #Column + ' LIKE N''%' + #Key + '%'''
)
END
SET #TableAndColums = REPLACE(#TableAndColums,#Column + '.' , '')
END
END
SET #SearchKeys = REPLACE(#SearchKeys,#Key + ',' , '')
END
--return found values
SELECT DISTINCT TargetId , DBname FROM #Results
END
For some reason it searches only for the first key ignoring all the rest keys. I can not find out why this is happening. Please help!
The very first thing I'll warn you about here is your procedure is wide open to injection attack. Injection attack is in and of itself a broad topic. If you're interested, I suggest reading this article. If you do absolutely need this type of interface (i.e. you can't use static typed SQL or something like Entity Framework to take care of the queries for you), you must must MUST make sure that any strings being executed at run time (e.g. #column, #table, #key) are parametrized or bracketed. This procedure, as written, will also fail when an inputted table does not contain an ID column or when an inputted column doesn't exist.
http://www.sommarskog.se/dynamic_sql.html
In terms of how you're doing string splitting, I'd look at the article below. While there's no way to eliminate the need to loop over each table, by putting all your search strings into a table using a string splinting function like the ones mentioned in this article, you can search all search conditions on a single table at once. Something like this:
select *
from #SearchConditions a
inner join dbo.TargetTable b
on b.Name like '%' + a.SearchKey + '%'
http://www.sqlservercentral.com/articles/Tally+Table/72993/

SQL syntax error

Im using Microsoft SQL Server which I think is T-SQL or ANSI SQL.
I want to search a database with a string. The matches that fit the begging of the string should come first then sort alphabetically.
I.e. If the table contains FOO, BAR and RAP
a search for the string 'R' should yield:
RAP
BAR
In that order.
Here is my attempt:
SELECT Name
FROM MyTable
WHERE (Name LIKE '%' + #name + '%')
ORDER BY (IF(Name LIKE #name + '%',1,0))
The error message is: "must declare scalar variable #name"
declare #name varchar(10)
set #name='R'
SELECT Name
FROM (select 'foo' as name union select 'RAP' union select 'BAR') MyTable
WHERE (Name LIKE '%' + #name + '%')
ORDER BY charindex(#name ,name)
.
DECLARE #name VARCHAR(MAX);
SET #name = 'foo';
SELECT Name
FROM MyTable
WHERE Name LIKE '%' + #name + '%'
ORDER BY CASE WHEN Name LIKE #name + '%' THEN 1 ELSE 0 END;
Other solutions seem to miss the "sort alphabetically" part:
DECLARE #Search VARCHAR(MAX)
SET #Search = 'R'
SELECT 0, Name
FROM MyTable
WHERE Name LIKE #Search + '%'
UNION ALL
SELECT 1, Name
FROM MyTable
WHERE Name like '%_' + #Search + '%'
ORDER BY 1, 2
Seems that you missed variable declaration:
DECALRE #name varchar(50) -- adjust type and length of variable
SET #name = 'phrase' -- for MSSQL 2008 you can do it in one line

How to adjust SQL LIKE function?

I want to make this kind of query:
create procedure something
#name varchar(13)
as
begin
select *
from WORKER
where NAME LIKE "%#name%"
end
For input #name=ho, I want output every row that contains NAME which sounds ho,
for example HOuse, soHO, broHOw...
Select * from WORKER where Name Like '%' + #name + '%'
create procedure something
#name varchar(13)
as
begin
select * from WORKER
where NAME LIKE '%' + #name + '%'
end