I've got a sproc (MSSQL 2k5) that will take a variable for a LIKE claus like so:
DECLARE #SearchLetter2 char(1)
SET #SearchLetter = 't'
SET #SearchLetter2 = #SearchLetter + '%'
SELECT *
FROM BrandNames
WHERE [Name] LIKE #SearchLetter2 and IsVisible = 1
--WHERE [Name] LIKE 't%' and IsVisible = 1
ORDER BY [Name]
Unfortunately, the line currently running throws a syntax error, while the commented where clause runs just fine. Can anyone help me get the un-commented line working?
If you are using a Stored Procedure:
ALTER PROCEDURE <Name>
(
#PartialName VARCHAR(50) = NULL
)
SELECT Name
FROM <table>
WHERE Name LIKE '%' + #PartialName + '%'
Joel is it that #SearchLetter hasn't been declared yet? Also the length of #SearchLetter2 isn't long enough for 't%'. Try a varchar of a longer length.
As Andrew Brower says, but adding a trim
ALTER PROCEDURE <Name>
(
#PartialName VARCHAR(50) = NULL
)
SELECT Name
FROM <table>
WHERE Name LIKE '%' + LTRIM(RTRIM(#PartialName)) + '%'
But in my opinion one important thing.
The "char(number)" it's lenght of variable.
If we've got table with "Names" like for example [Test1..Test200] and we declare char(5) in SELECT like:
DECLARE #variable char(5)
SET #variable = 'Test1%'
SELECT * FROM table WHERE Name like #variable
the result will be only - "Test1"! (char(5) - 5 chars in lenght; Test11 is 6 )
The rest of potential interested data like [Test11..Test200] will not be returned in the result.
It's ok if we want to limit the SELECT by this way.
But if it's not intentional way of doing it could return incorrect results from planned
( Like "all Names begining with Test1..." ).
In my opinion if we don't know the precise lenght of a SELECTed value, a better solution could be something like this one:
DECLARE #variable varchar(max)
SET #variable = 'Test1%'
SELECT * FROM <table> WHERE variable1 like #variable
This returns (Test1 but also Test11..Test19 and Test100..Test199).
This works for me on the Northwind sample DB, note that SearchLetter has 2 characters to it and SearchLetter also has to be declared for this to run:
declare #SearchLetter2 char(2)
declare #SearchLetter char(1)
Set #SearchLetter = 'A'
Set #SearchLetter2 = #SearchLetter+'%'
select * from Customers where ContactName like #SearchLetter2 and Region='WY'
DECLARE #SearchLetter2 char(1)
Set this to a longer char.
We can write directly too...
DECLARE #SearchLetter CHAR(1)
SET #SearchLetter = 'A'
SELECT *
FROM CUSTOMERS
WHERE CONTACTNAME LIKE #SearchLetter + '%'
AND REGION = 'WY'
or the following way as well if we have to append all the search characters then,
DECLARE #SearchLetter CHAR(1)
SET #SearchLetter = 'A' + '%'
SELECT *
FROM CUSTOMERS
WHERE CONTACTNAME LIKE #SearchLetter
AND REGION = 'WY'
Both these will work
I had also problem using local variables in LIKE.
Important is to know: how long is variable.
Below, ORDER_NO is 50 characters long, so You can not use: LIKE #ORDER_NO, because in the end will be spaces.
You need to trim right side of the variable first.
Like this:
DECLARE #ORDER_NO char(50)
SELECT #ORDER_NO = 'OR/201910/0012%'
SELECT * FROM orders WHERE ord_no LIKE RTRIM(#ORDER_NO)
It may be as simple as LIKE '%%[%3]%%' being [%3] the input variable.
This works for me with SAP B1 9.1
I ran into a similar problem. I needed to use just a small piece of a URL saved in my database where the front and ends were irrelevant.
I first attempted to use:
DECLARE #variable VARCHAR(250) = %x%;
SELECT * FROM tblone WHERE column1 LIKE '#variable'
However, this returned the error:
Arithmetic overflow error converting numeric to data type varchar
My working query was formatted:
DECLARE #variable VARCHAR(1000) = x;
SELECT * FROM tblone WHERE column1 LIKE '%'+#variable+'%'
Related
I did following store procedure using dynamic query, see the following blueprint of code
ALTER PROCEDURE [dbo].[usp_Report] (
#LocationId INT = NULL
,#UserId INT = NULL)
DECLARE #miscquery NVARCHAR (MAX);
begin
SET #miscquery='
SELECT
,A.AgreementNumber AS Contract
,A.AgreementId
FROM tblAgreement A
WHERE
AND (A.IsDeleted = 0 or A.IsDeleted is null)
AND (
(
' + convert(NVARCHAR(30), #LocationId) + ' IS NULL
AND (
A.CheckoutLocation IN (
SELECT LocationId
FROM [dbo].[tblUserLocations]
WHERE UserID = ' + convert(VARCHAR(10), #userId) +'
AND IsDeleted = 0
)
OR A.CheckoutLocation IS NULL
)
)
OR A.CheckoutLocation = ' + convert(VARCHAR(10), #LocationId) +'
)'
EXEC (#miscquery)
end
)
here when i execute the query with #Locationid is null, results doesn't return table, it returns like following
(63 rows affected)
(2325 rows affected)
please help me. thank you
The code you have there cannot be your actual code, firstly because right at the start you try to set a variable called #miscquery before you declare it. There's also no reason for this code to be dynamic, so it's clear you're doing some other stuff as well.
I will take it as a given that for some reason you "need" dynamic SQL. I will put in the standard warning about sanitising your inputs. That was it.
OK. Even if #miscquery had been declared, the code as written will not produce any results. It will either throw a syntax error, or do nothing, depending on your setting for concat_null_yields_null.
Let's take the likely case: you have the default setting for this, which means that when you concatenate a varchar to null, the result is null.
Observe the following code:
declare #locationId int = null;
select 'this sentence ends with...' + convert(nvarchar(30), #locationId);
What will be the output?
"This sentence ends with... null"
"This sentence ends with..."
null
The answer is 3. And notice: that's not a string with the value "null". That's just null. When you convert the null value to a string, you don't get a string with the value "null", you get the null value.
OK, so now we try to add null to the end of our string. When you try to concatenate the null value to a string with the + operator, the entire result is null.
Therefore, your entire #miscquery variable is null at the end of the assignment.
So what you are then doing is the same as this:
declare #myquery varchar(max) = null;
exec sp_executesql #myquery
Which is valid, and doesn't throw any error, but does nothing. Then the rest of your code does whatever it does, and produces the results you see.
if concat_null_yields_null was set to off then you would get a syntax error, because the resulting text would not be valid SQL when you handed it to sp_executesql.
As Dan said, the best and safest solution would be to parameterize your inputs. But putting that aside, the solution you need would look something like the following. In the iif() function, I look at the value of #locationId. If it is null, then I want the string "null". If it is not null, then I want the string conversion of whatever value it has.
declare #locationId int = null;
declare #query varchar(max) =
'select * from mytable where '
+ iif(#locationId is null, 'null', convert(nvarchar(30), #locationId))
+ ' is null';
print #query;
I need to fetch max length of First_name and put it into #sq i am getting an error.
Declare #sq nvarchar(max)
Set #sq=''
SELECT MAX(LEN(FIRST_NAME)) FROM #table1
Drop table #t
SELECT CASE WHEN LEN(SEQ_NUM) = 0 THEN NULL ELSE SEQ_NUM END AS REC_NUM,
CASE WHEN LEN(FIRST_NAME) = 0 THEN NULL ELSE CONVERT(CHAR(Select #sq)),RTRIM(UPPER(FIRST_NAME))) END AS FIRST_NAME
into #t
from #tabel1
There's a few problem with this SQL. If we start with the first statement:
Set #sq=''SELECT MAX(LEN(FIRST_NAME)) FROM #table1
You have a couple of wayward single quotes here ('); not sure what they're doing. Secondly, if you're assigning a variables value from a dataset, the syntax is SELECT {Variable} = {expression} [,{Variable} = {expression} [,...]] FROM {etc} Thus you get:
SELECT #sq = MAX(LEN(FIRST_NAME))
FROM #table1;
The next statement, well, that's a mess. Firstly, there's also a wayward right parenthesis ()) here: RTRIM(UPPER(FIRST_NAME))) There should only be 2.
The expression CONVERT(CHAR(Select #sq)) is very wrong. CONVERT require 2 parameters, but only has one, and CHAR would return an character for the appropriate number provided. I.e. CHAR(65) returns A. I suspect you mean CONVERT(char,#sq) (you should really be declaring a length here!), however, #sq is already an nvarchar(max) (which is also pointless, as it's being assigned the value of an int). Thus I literally have no idea what you're trying to achieve here.
You need to assign the variable, like this:
Declare #sq int --LEN returns an int, not a varchar!
SELECT #sq = MAX(LEN(FIRST_NAME))
FROM #table1
I have variable called #prmclientcode which is nvarchar. The input to this variable can be a single client code or multiple client codes separated by comma. For e.g.
#prmclientcode='1'
or
#prmclientcode='1,2,3'.
I am comparing this variable to a client code column in of the tables. The data type of this column is numeric(6,0). I tried converting the variable data type like below
SNCA_CLIENT_CODE IN ('''+convert(numeric(6,0),#prmclientcode+''')) (The query is inside a dynamic sql).
But when I try executing this I get the error
Arithmetic overflow error converting nvarchar to data type numeric.
Can anyone please help me here!
Thanks!
You need to convert the numeric(6,0) column to nvarchar data type. You can use below scrip to convert it to nvarchar, before processing:
SNCA_CLIENT_CODE IN ('''+convert(cast( numeric(6,0) as nvarchar(max) ),#prmclientcode+'''))
Please try with the below code snippet.
DECLARE #ProductTotals TABLE
(
ProductID int
)
INSERT INTO #ProductTotals VALUES(1)
INSERT INTO #ProductTotals VALUES(11)
INSERT INTO #ProductTotals VALUES(3)
DECLARE #prmclientcode VARCHAR(MAX)='1'
SELECT * FROM #ProductTotals
SELECT * FROM #ProductTotals WHERE CHARINDEX(',' + CAST(ProductID AS VARCHAR(MAX)) + ',' , ',' + ISNULL(#prmclientcode,ProductID) + ',') > 0
Let me know if any concern.
use following code in order to separate your variable:
DECLARE
#T VARCHAR(100) = '1,2,3,23,342',
#I int = 1
;WITH x(I, num) AS (
SELECT 1, CHARINDEX(',',#T,#I)
UNION ALL
SELECT num+1,CHARINDEX(',',#T,num+1)
FROM x
WHERE num+1<LEN(#T)
AND num<>0
)
SELECT SUBSTRING(#T,I,CASE WHEN num=0 THEN LEN(#T)+1 ELSE num END -I)
FROM x
Use can use either table function or dynamic sql query, both options will work.
Let me know if you need more help
I have following table "Managers" (simplified):
ID, int
Name, nvarchar(100)
In a stored procedure that has one argument ("Search", type nvarchar), I want to select every row where
The ID-Column is exactly #Search OR
The Name-Column contains #Search.
At the moment, my select in the stored procedure looks something like this:
SELECT ID, Name FROM Managers WHERE
(ISNUMERIC(#Search) = 1 AND [ID] = CAST(#Search AS INT)) Or
Contains([Name], #Search)
If I call the stored procedure with #Search = 1321 (example), the select works.
But if I have a #Search - parameter that is not numeric (example "HES"), I get the following error:
Conversion failed when converting the nvarchar value 'HES' to data type int.
How can I fix this?
Thanks in advance
Raphi
SELECT ID, Name FROM Managers
WHERE [ID] = CASE
WHEN ISNUMERIC(#Search) = 1 AND #Search NOT LIKE '%.%' THEN CAST(#Search AS INT)
ELSE -1
END
OR Contains([Name], #Search)
I want to include column in where clause depending on the condition.
e.g
select * From emp
where id=7,
and if(code is not null) then code=8;
how can i do this in sql server
If I understand you correct, you could make use of COALESCE.
COALESCE()
Returns the first nonnull expression
among its arguments.
SQL Statement
SELECT *
FROM emp
WHERE id=7
AND code = COALESCE(#code, code)
If code is a column rather than a variable the query in your question would be rewritten as follows.
SELECT *
FROM emp
WHERE id=7 AND (code IS NULL OR code=8)
You'll probably have to create a query dynamically, as a string, and then use the Execute method to actually execute it. This approach has some potentially optimization issues, but it's commonly done. You might wan to Google T-SQL Dynamic Query, or something like that.
Also use this in case of Null value in #var1.
Select * from ABC where Column1 = isNull(#var1, Column1)
here is the example:
declare #SQL varchar(500)
declare #var1 int
set int = 1
set #SQL = 'Select * from ABC Where 1 = 1'
if(#var1 = 1)
set #SQL + #SQL ' And column1 = ' #var1
exec(#SQL)
You can use COALESCE function.
Well,
I don't know if i understood your question, but i guess that you want to include the value of the code column in the results.
If i'm right it can be done in the select part instead of the where clause. i. e.
Select ..., case when code is not null then 8 else code end as code from emp where id = 7
The other interpretation is that you want to filter rows where code <> 8,that would be
Select * from emp where id = 7 and (code is null OR code = 8)