How to pass parameter to stored procedure - sql

I am using SQL Server 2008 Enterprise on Windows Server 2008 Enterprise. In the stored procedure, I need to pass parameter to a select-where-like statement. For example,
#department is store procedure input parameter, its type is varchar(20),
select * from sometable where somecolumn LIKE '%#department%'
but seems my statement above does not work, any ideas how to pass parameter #department to like statement?
thanks in advance,
George

select * /*But don't use * in production!*/
from sometable
where somecolumn
LIKE '%' + #department + '%'

You concatenate the strings:
select * from sometable where somecolumn LIKE '%' + #department + '%'

It's a variable, it goes outside the quotes.
select * from sometable where somecol like '%' + #department + '%'
Or, more preferably, add the %s to the variable and just use it directly

try:
select * from sometable where somecolumn LIKE '%' + #department + '%'

You could do something like this:
select * from sometable where somecolumn LIKE '%' + #department + '%'

select * from sometable
where CHARINDEX(#department,somecolumn)>0
You can also use the CHARINDEX function.

Related

MSSQL query search with keyword list

I got one table that contains all information about products. I need to list all articles with a matching keywords (in this case the brand name) in a specific column. Is it possible to initiate some kind of a 'list' with all brand names that I can use for this operation? chaning OR for all brands seems kinda bad.
In the second step I only need to see all articles that does not contain a specific word order before they keywords from the first step.
DECLARE #brand NVARCHAR =
'bmw, toyota, mercedes'
SELECT [Artikelnum]
FROM [dbo].[LAGER]
WHERE [XWebtexke] like '%' + #brand +'%' AND [XWebtexke] NOT LIKE '%suited for%'
GO
Thats what I got so far, but it does not work in the way I need it.
DECLARE #brand NVARCHAR =
'bmw, toyota, mercedes'
select * from (
SELECT [Artikelnum]
FROM [dbo].[LAGER]
WHERE [XWebtexke] NOT LIKE '%suited for%' )t4
WHERE [XWebtexke] like '%' + #brand +'%'
GO
DECLARE #brand NVARCHAR =
'bmw, toyota, mercedes'
select * from (
SELECT [Artikelnum]
FROM [dbo].[LAGER]
WHERE [XWebtexke] NOT LIKE '%suited for%' )t4
WHERE t4.[XWebtexke] like '%' + #brand +'%'
GO
Realized you need all the keywords to match. Here is the solution for that.
You need to split the brand variable, try this:
DECLARE #brand NVARCHAR(200) = 'bmw, toyota, mercedes'
;WITH CTE as
(
SELECT '%'+ t.c.value('.', 'VARCHAR(2000)')+'%' val
FROM (
SELECT x = CAST('<t>' +
REPLACE(#brand, ', ', '</t><t>') + '</t>' AS XML)
) a
CROSS APPLY x.nodes('/t') t(c)
)
SELECT [Artikelnum]
FROM [dbo].[LAGER]
WHERE
not exists(SELECT * FROM CTE WHERE [XWebtexke] not like val)
and [XWebtexke] NOT LIKE '%suited for%'
I am assuming there is always a space after the comma, you can adjust the code with ease if that is not always the case.
In sqlserver 2016 you can use STRING_SPLIT instead of the split used in my answer

How can we replace , with ',' in T-Sql

How can we replace , with ',' in T-Sql
i am passing 'a,b,c' as a parameter and i am trying to replace , with ',' so that i can get the output as 'a','b','c'
i have the workaround where we can put it in a temp table and read from that table but i was curious to know if we can achieve it directly using the replace function in Sql server.
Thanks in advance
You could use
select ''''+replace(column1,',',''',''') +''''
from tablename
However, there may be more efficient ways to do this.
Let's say you were using the parameter
DECLARE #Param NVARCHAR(100)
You can simply perform the following operation:
SET #Param = (SELECT CONCAT('''', REPLACE(#Param ,',',''','''), '''') )
I haven't tested this on SQL yet, but I think this should do the job
Try like this,
SELECT Column1 AS CommaSeparatedColumn
,'''' + replace(Column1, ',', ''',''') + '''' AS CommaWithinSingleQuotesSeparatedColumn
FROM (
VALUES ('a,b,c,d')
) T(Column1)
WHERE Column1 LIKE '%'
OR Column1 LIKE '%' + REPLACE(Column1, ',', '%')

How to make my search for multiple columns procedure more efficient?

I have a stored procedure that searches across multiple columns in a combined table.
It works, however, it takes 15 seconds to search for a value in that combined table. The table takes 9 seconds to load so I'm not sure, maybe it's because my table too big?
So I'm just wondering if there's a way to make this query runs faster.
This is my stored procedure:
create procedure LRMWEB_Search
#input nvarchar(1500)
AS
SET NOCOUNT ON;
SELECT tr.ResourceID ,
tr.ProjectFile,
tr.ResourceFile,
tr.ResourceName,
trt.Culture,
trt.TranslatedFlag,
trt.TranslatedValue,
tr.Comments,
tr.IsApproved
FROM tblResourcesTranslated_NEW trt
INNER JOIN tblResources_NEW tr ON trt.ResourceID = tr.ResourceID
where tr.ResourceID like '%'+ #input + '%'
OR tr.ProjectFile like '%'+ #input + '%'
OR tr.ResourceFile like '%'+ #input + '%'
OR tr.ResourceName like '%'+ #input + '%'
OR tr.ResourceValue like '%'+ #input + '%'
OR tr.Comments like '%'+ #input + '%'
OR trt.Uid like '%'+ #input + '%'
OR trt.TranslatedValue like '%'+ #input + '%'
;
Any use of like precludes an index, unless it has a fixed prefix with a wildcard suffix, such as where foo like 'bar%'. Your like expressions (e.g., '%xxx%' ) do not meet that requirement.
As a result, while the join criteria may well have a covering index, nothing else does and so a table scan of the join tables is required.
In a nutshell, there is no way to fix performance outside of either
rethinking what you're doing, or
using something like a full text search
SELECT tblResources_NEW.ResourceID
,tblResources_NEW.ProjectFile
,tblResources_NEW.ResourceFile
,tblResources_NEW.ResourceName
,tblResourcesTranslated_NEW.Culture
,tblResourcesTranslated_NEW.TranslatedFlag
,tblResourcesTranslated_NEW.TranslatedValue
,tblResources_NEW.Comments
,tblResources_NEW.IsApproved
FROM
(
SELECT
tblResources_NEW.ResourceID
,tblResources_NEW.ProjectFile
,tblResources_NEW.ResourceFile
,tblResources_NEW.ResourceName
,tblResources_NEW.Comments
,tblResources_NEW.IsApproved
FROM tblResources_NEW
WHERE
tblResources_NEW.ResourceID like '%'+ #input + '%'
OR tblResources_NEW.ProjectFile like '%'+ #input + '%'
OR tblResources_NEW.ResourceFile like '%'+ #input + '%'
OR tblResources_NEW.ResourceName like '%'+ #input + '%'
OR tblResources_NEW.ResourceValue like '%'+ #input + '%'
OR tblResources_NEW.Comments like '%'+ #input + '%'
) AS tblResources_NEW
INNER JOIN
(
SELECT
tblResourcesTranslated_NEW.ResourceID
,tblResourcesTranslated_NEW.Culture
,tblResourcesTranslated_NEW.TranslatedFlag
,tblResourcesTranslated_NEW.TranslatedValue
FROM tblResourcesTranslated_NEW
WHERE
tblResourcesTranslated_NEW.Uid like '%'+ #input + '%'
OR tblResourcesTranslated_NEW.TranslatedValue like '%'+ #input + '%'
) AS tblResourcesTranslated_NEW ON tblResourcesTranslated_NEW.ResourceID=tblResources_NEW.ResourceID
If You insist on having one input for all fields, I would at least boost some performance by doing dynamic SQL.
Alter PROCEDURE LRMWEB_Search
(
#input nvarchar(1500)
)
AS
declare #sql varchar(2000);
SET NOCOUNT ON;
set #sql = 'SELECT
tblResources_NEW.ResourceID,
tblResources_NEW.ProjectFile,
tblResources_NEW.ResourceFile,
tblResources_NEW.ResourceName,
tblResourcesTranslated_NEW.Culture,
tblResourcesTranslated_NEW.TranslatedFlag,
tblResourcesTranslated_NEW.TranslatedValue,
tblResources_NEW.Comments,
tblResources_NEW.IsApproved
FROM
tblResourcesTranslated_NEW INNER JOIN
tblResources_NEW ON tblResourcesTranslated_NEW.ResourceID=tblResources_NEW.ResourceID
where ';
-- here I would concatenate all your string conditions
if (ISNUMERIC(#input)= 0)
Begin
. . . . . . .
End
-- here I would concatenate all your numeric conditions
if (ISNUMERIC(#input)= 1)
Begin
set #sql = #sql + ' OR tblResources_NEW.ResourceID like ''%#1%''';
. . . . .
End
-- call to execute
EXECUTE sp_executesql #sql, N'#1 varchar', #1 = #input;
This should give you at least some boost by excluding unneeded searches. But really, you should do something like this by using single parameter for every condition. Than you can exclude those that are Null from building into string.
But, again, this design is BAD.

SQL parameterized query not returning correct results

I have a view in my DB and the view has a row I am trying to search for. I've tested it in sql server and it returned the correct result. However when I try it with parameters from vb it won't return anything. The Sql code that I get a query to return a correct result looks like
SELECT *
FROM
(SELECT
ROW_NUMBER() OVER (ORDER BY groupID DESC) AS Row, *
FROM
SchedulingGroup_VIEW
WHERE
(scheduled = 1)
AND ((building LIKE '%dunn%') OR (room LIKE '%dunn%')
OR (requestBy LIKE '%dunn%') OR (requestFor LIKE '%dunn%')
OR (groupID LIKE '%dunn%') OR (description LIKE '%dunn%'))
AND (NOT EXISTS (SELECT gID FROM facilitiesForm
WHERE facilitiesForm.gID <> gID))) AS TMP
WHERE
(Row BETWEEN 0 AND 100)
The SQL with parameter looks like
SELECT * FROM (SELECT ROW_NUMBER() OVER (ORDER BY groupID DESC) AS Row, *
FROM schedulingGroup_VIEW
WHERE (scheduled = 1) AND
( (building LIKE '%' + #search + '%')
OR (room LIKE '%' + #search + '%')
OR (requestBy LIKE '%' + #search + '%')
OR (requestFor LIKE '%' + #search + '%')
OR (groupID LIKE '%' + #search + '%')
OR (description LIKE '%' + #search + '%'))
AND
(NOT EXISTS (SELECT gID FROM facilitiesForm
WHERE facilitiesForm.gID <> gID))) AS TMP WHERE (Row BETWEEN 0 AND 100)
sqlComm.Parameters.AddWithValue("#search", info.search)
with info.search = "dunn".
The sql query returns the appropriate row but the vb.net with parameters returns nothing.
Move your wildcards (i.e. your % characters) into your VB.net string before you pass it as a parameter.
For example, do this in VB.net code...
sqlComm.Parameters.AddWithValue("#search", "%" + info.search + "%");
And in your SQL when you use the #search parameter in the LIKE statement, don't add in wildcards, like shown below...
WHERE building LIKE #search
See this SO post which is essentially the same question...
How to use wildcards in SQL query with parameters

SQL Server statement Where myfield content giving sub-string

I'm looking for a SQL Server statement to retrieve records Where myfield content giving sub-string.
Another possibility is to use LIKE:
SELECT
MT.column_1,
....
FROM
My_Table MT
WHERE
some_column LIKE '%' + #search_string + '%'
You can use CharIndex
Select * From YourTable
Where
CharIndex('yoursubstring', myfield) > 0
Try PatIndex.
SELECT *
FROM Table
WHERE patindex('%string%', data ) > 0
select * from mytable where myfield like '%literalstring%'
or
select * from mytable where myfield like '%' + #stringvar + '%'
...not really clear on whether your substring is a literal or a variable