Temp variable used in select Query - sql

I tried to retrieve data from the table using a temp variable. The temp variable returns correct data but when tried to use it in Query it is not returning correct data set.
I have tried retrieving data using hard coded temp value in the query, it works fine. Can anyone help me out to find the issue here.?
Below is my code I have tried
Declare #tempwordFinal varchar(50)
select #tempwordFinal = ''''+'%'+'The Big Bang'+'%'+''''
select #tempwordFinal --here the output is - '%The Big Bang%'
SELECT * from MasterProgram where ProgramTitle like #tempwordFinal --not working
SELECT * from MasterProgram where ProgramTitle like '%The Big Bang%' -- working

Because #tempwordFinal variable has single quotes at the start and end. So it expects the data in ProgramTitle column to have single quotes at the start and end. Except the wildcards whatever present inside the variable will be considered as data that's why it is failing.
select #tempwordFinal --here the output is - '%The Big Bang%'
^ ^
Try this way
Declare #tempwordFinal varchar(50)
select #tempwordFinal = '%The Big Bang%'
select 1 where 'The Big Bang' like #tempwordFinal
When you use variables for varchar datatype we don't need single quotes. Single quotes are required only when you hard code the string constants

The problem was with your (escaped) extra apostrophes. Like this ''''. You don't need those unless you are looking for words in the database which explicitly contain apostrophes. The corrected code looks like this:
Declare #tempwordFinal As Varchar(50);
Set #tempwordFinal = '%The Big Bang%';
Select #tempwordFinal; -- %The Big Bang%
SELECT * from MasterProgram where ProgramTitle like #tempwordFinal;

Related

Grafana - SQL 2014 - MSSQL - How to insert the result of a variable templating in a table

I want to rework a result of templating variable that looks like this:
'string1','string2','string3'
I try to add few characters like 'test', before every string.
In fact if I could just get a way to insert all these strings in a table I would be fine but I fail at this step.. BTW It must work for n string in the result.
Ideal result would be:
select *
From tbl
returning this (I don't care if column as a title):
colName
'teststring1'
'teststring2'
'teststring3'
but just beeing able to insert it in a table would be nice I'll handle the update of the strings.
If your string is like 'string1,string2,string3' and working with the higher version of SQL Server then you can try the following way.
declare #string as varchar(120) = 'string1,string2,string3'
select
'test' + value
from string_split (#string, ',')
Here is the live db<>fiddle demo.

XML Query with a variable in WHERE

I have this code that works well. But I want to have a variable to change its value in run time. I want the output xml file in C#.
declare #MySearch nvarchar(50)
set #MySearch='بودان'
SELECT ID, Family
FROM Table_1
where freetext(Family, #MySearch, LANGUAGE 1025)
FOR XML RAW ('Employee'), ROOT ('Employees'), ELEMENTS XSINIL;
EDITED:
I ran this code and got this error:
Null or empty full-text predicate.
I want the output xml file in C#.
declare #MySearch nvarchar(50)
--set #MySearch=N'بودان'
SELECT ID, Family
FROM Table_1
where freetext(Family, #MySearch, LANGUAGE 1025)
FOR XML RAW ('Employee'), ROOT ('Employees'), ELEMENTS XSINIL;
The "N" makes the difference, and you need it twice...
Try this:
DECLARE #v1 VARCHAR(10)='بودان';
DECLARE #v2 VARCHAR(10)=N'بودان';
DECLARE #nv1 NVARCHAR(10)='بودان';
DECLARE #nv2 NVARCHAR(10)=N'بودان';
SELECT #v1,#v2,#nv1,#nv2;
The result
????? ????? ????? بودان
Only the very last attempt will show what you need...
The reason: A normal string SET #v='MyString' is not handled as UNICODE
It is neither enough to declare the variable as NVARCHAR nor is it enough to store a unicode literal like N'SomeText'.
EDIT:
After long disucussion in comments the final sentence to solve the issue was this:
Of course you must be connected with the DB to do this!
What ever you want to with your database, first you need an opened connection.

Using a string of quoted values in a variable for a SQL WHERE CLAUSE

The answer escapes me...maybe because it is not possible...
Example that works...
SELECT * FROM TABLEA WHERE FIELD1 IN ('aaa','bbb','ccc')
Example that does not work...
Attempt to leverage variable so that I can define the values once in a string of statements
DECLARE #ListValues VARCHAR(50)
SET #ListValues = '''aaa'',''bbb'',''ccc'''
SELECT * FROM TABLEA WHERE FIELD1 IN (#ListValues)
This is is obviously only a small part of the equation and for other reasons...
I cannot leverage a table for the values and change this to a true sub-query
The closest question I could find was this one... but does not cover my requirements obviously...
Storing single quotes in varchar variable SQL Server 2008
Thanks in advance.
You can do this using dynamic SQL:
DECLARE #ListValues VARCHAR(MAX)
,#SQL VARCHAR(MAX)
SELECT #ListValues = '''aaa'',''bbb'',''ccc'''
,#SQL = 'SELECT * FROM TABLEA WHERE FIELD1 IN ('+#ListValues+')'
EXEC (#SQL)
It doesn't work because the IN operator expects a list of items - here strings.
What you're supplying with your #ListValues variable however is a single string - not a list of strings.
What you could do is use a table variable and store your values in it:
DECLARE #ListOfValues TABLE (ItemName VARCHAR(50))
INSERT INTO #ListOfValues(ItemName)
VALUES('aaa'), ('bbb'), ('ccc')
SELECT *
FROM TABLEA
WHERE FIELD1 IN (SELECT ItemName FROM #ListOfValues)
Build your whole SQL query dynamically (say it's stored in a string variable #sql),
and then execute it with EXEC (#sql). Better yet, use the sp_executesql SP
because this approach is more secure (less prone to SQL injection) than EXEC.
See: sp_executesql
The IN operator in SQLServer expect a list of values, your variable is a single string, the query parsed will be different
SELECT * FROM TABLEA WHERE FIELD1 IN ('aaa','bbb','ccc')
SELECT * FROM TABLEA WHERE FIELD1 IN ("'aaa','bbb','ccc'")
Attention: the double quotes are there only for readability, to get the string with single quote in it.
if you know a programming language the first one is like searching in an array, the second is a string.
To store a list in your variable it need to a table
DECLARE #varTable TABLE (field1 varchar())
So that you can use it in your IN
SELECT * FROM TABLEA WHERE FIELD1 IN (SELECT field1 FROM #varTable)
To add values to the table variable use an INSERT statament like usual for tables.

Complex query filter using Like() in T-SQL

I'm writing a SQL script that we want our accounting team to be able to edit, without dealing with engineering.
The general idea is to have a .sql script, which defines some variables at the top of the query, and then has several complex queries below it that use those variables.
The problem we have is that we want the accounting team to be able to specify the filter to use. For example:
DECLARE #year INT
DECLARE #month INT
DECLARE #filter VARCHAR(30);
SET #year = 2010
SET #month = 7
SET #filter = '%test%'
Here the team can change the month and the year that the subsequent queries return. They can also define ONE filter element, in this example, excluding any records where the username has the string 'test' in it.
My question is whether or not there is a way to specify OR's to a LIKE(). Eg, ideally we'd have the #filter variable as something like '%test%, or %other%. Now I know that's not real syntax, but I'm wondering if there is syntax that lets me achieve that. I've scowered MSDN on the LIKE() syntax with no joy. Should I use some different query expression?
Probably the simplest thing to do would be to just have multiple parameters, though it's not pretty:
SET #filter_1 = '%test%'
SET #filter_2 = '%foo%'
SET #filter_3 = '%'
SET #filter_4 = '%'
SELECT *
FROM BAR
WHERE var LIKE #filter_1
OR var LIKE #filter_2
OR var LIKE #filter_3
OR var LIKE #filter_4
OR var LIKE #filter_5
By defaulting them to %, they will always match by default.
You could also use dynamic SQL and a local table variable. Basically, create a local table with one column, allow them to change the INSERT statements into that table, then define a loop that iterates over the contents of that table to dynamically generate the LIKE clauses. It would work, but it would be a bit more code. The example above is quick and dirty, but I'd guess it's probably sufficient for what you need to do.
I'd use a join with a LIKE predicate. You can execute the following code sample in a query window to see how this works:
DECLARE #tblFilter TABLE
(sFilter nvarchar(MAX) NOT NULL);
INSERT #tblFilter
SELECT * FROM (VALUES ('%one%'), ('%two%'), ('%three%')) v(s);
DECLARE #tblData TABLE
(iId int NOT NULL PRIMARY KEY IDENTITY,
sData nvarchar(MAX));
INSERT #tblData(sData)
SELECT * FROM (VALUES ('one'), ('two three'), ('four')) v(s);
SELECT DISTINCT iId
FROM #tblData d
JOIN #tblFilter f ON d.sData LIKE f.sFilter;
I assume that the different query strings are in the #tblFilter table, which could be a TVP, coming from XML values, from comma-separated values, from a temp table or whatever.

how to write the store procedure for searching (CSV)?

how can i write the store procedure for searching particular string in a column of table, for given set of strings (CSV string).
like : select * from xxx where tags like ('oscar','rahman','slumdog')
how can i write the procedure for that combination of tags.
To create a comma seperated string...
You could then apply this list to Oded example to create the LIKE parts of the WHERE cluase on the fly.
DECLARE #pos int, #curruntLocation char(20), #input varchar(2048)
SELECT #pos=0
SELECT #input = 'oscar,rahman,slumdog'
SELECT #input = #input + ','
CREATE TABLE #tempTable (temp varchar(100) )
WHILE CHARINDEX(',',#input) > 0
BEGIN
SELECT #pos=CHARINDEX(',',#input)
SELECT #curruntLocation = RTRIM(LTRIM(SUBSTRING(#input,1,#pos-1)))
INSERT INTO #tempTable (temp) VALUES (#curruntLocation)
SELECT #input=SUBSTRING(#input,#pos+1,2048)
END
SELECT * FROM #tempTable
DR0P TABLE #tempTable
First off, the use of like for exact matches is sub-optimal. Might as well use =, and if doing so, you can use the IN syntax:
select * from xxx
where tags IN ('oscar', 'rahman', 'slumdog')
I am guessing you are not looking for an exact match, but for any record where the tags field contains all of the tags.
This would be something like this:
select * from xxx
where tags like '%oscar%'
and tags like '%rahman%'
and tags like '%slumdog%'
This would be not be very fast or performant though.
Think about moving this kind of logic into your application, where it is faster and easier to do.
Edit:
Following the comments - there are lots of examples on how to parse delimited strings out there. You can put these in a table and use dynamic sql to generate your query.
But, this will have bad performance and SQL Server will not be able to cache query plans for this kind of thing. As I said above - think about moving this kind of logic to application level.