How to bind variable in string in SQL query? - sql

I am using SQL Developer. When I want to bind value. Normally I use following syntax:
SELECT * FROM table WHERE column = :bindvalue
but, I don't know how to do that in string. The following query does not work.
SELECT * FROM table WHERE column like '%:bindvalue%'
Why do I need it? Because my program runs a query in python and assigns something to bind variable:
curr.execute('''SELECT * FROM table WHERE column''' = :bindvalue, bindvalue=somevalue)

Concatenate the prefix/suffix with the bind variable:
SELECT * FROM table WHERE column like '%' || :bindvalue || '%'

Related

LIKE clause applied to a DB Type in Stored Procedure

I have created the following Type:
CREATE TYPE dbo.expressions
AS TABLE
(
expression varchar(255)
);
GO
How can I, in a Stored Procedure, use the n types that I receive and do, with each one, an select with a like clause?
In terms of "programming" (and pseudo-code), would be something like this:
for each expression in expressions
rows+=select * from table where table.field LIKE '%' + expression[i] + '%'
I can always call the SP multiple times from my API but I was wondering if this is possible, and even faster, to do in SQL side.
You simply SELECT from / JOIN with an instance of the type. Assuming you have something like:
CREATE TYPE expressions AS TABLE (expression varchar(255));
CREATE PROCEDURE mysp(#expressions AS expressions) ...
You can use the variable like you would use a table:
SELECT *
FROM #expressions AS expressions
INNER JOIN yourtable ON yourtable.field LIKE '%' + expressions.expression + '%'
The above will allow you to use expression in select clause. Otherwise you can use the following:
SELECT *
FROM yourtable
WHERE EXISTS (
SELECT 1
FROM #expressions AS expressions
WHERE yourtable.field LIKE '%' + expressions.expression + '%'
)

Filter in select where values start with NIR_

I am trying to filter my result set to only return values which start with NIR_.
My SQL statement to do so is as follows
select * from run where name like %NIR_%
The result set also includes names like
NIRMeta_Invalid
NIRMeta_Position
I am not sure what I am doing wrong. I only need to select names which start with NIR_.
You need to escape the underscore in your LIKE pattern if you want it to be treated as a literal.
In SQL Server:
select * from run where name like 'NIR[_]%'
In MySQL and Oracle:
select * from run where name like 'NIR\_%'
If you want names that only start with NIR, then remove the first wildcard in the like pattern:
where name like 'NIR_%'
Note that _ is also a wildcard, so you probably want:
where name like 'NIR\_%'
You can use ESCAPE option to achieve this.
SELECT * FROM run WHERE name LIKE 'NIR#_%' ESCAPE '#'
Sample execution with the given data:
DECLARE #Run TABLE (name VARCHAR (100));
INSERT INTO #Run (name) VALUES
('NIR_MA'), ('NIR_RUN'), ('NIRMeta_Invalid'), ('NIRMeta_Position');
SELECT * FROM #Run WHERE name LIKE 'NIR#_%' ESCAPE '#'
Result:
name
-----
NIR_MA
NIR_RUN

How to do a conditional where clause with where in PL/SQL within Procedure

I have a pretty simple Stored Procedure that I am in trouble to do because i'm new to SQL and PL/SQL. I Have a table with a name column that is a varchar(55).
I discovered that if the user executes my procedure with an empty string as a paramter the LIKE statment brings all rows from TABLE1
SELECT *
FROM TABLE1
WHERE COLUMN LIKE VARIABLE || '%'
AND...
So I tried to change the query so if the VARIABLE is passed with a empty string it can still perform other conditions in the where statment.
SELECT *
FROM TABLE1
WHERE (VARIABLE <> '' AND COLUMN LIKE VARIABLE || '%')
AND...
But now wherever I pass as variable ('', NULL, 'anystring') I get no rows returned.
How can I build a query that validates if the variable is different of empty string and if it is it performs the LIKE statment with the variable correctly?
If I understand you correctly, it is not difficult thing to do. You can use conditional WHERE clause using CASE WHEN. So your query will support different scenarios, something like this:
SELECT *
FROM TABLE1
WHERE (CASE WHEN variable IS NULL AND column IS NULL THEN 1
WHEN variable LIKE '%' AND column LIKE variable||'%' THEN 1
ELSE 0
END) = 1
AND...
Basically, it checks if the variable = '' then it will compare the column against ''. Otherwise, it will compare it against variable||'%'.
Notice, Oracle treats empty string of the type VARCHAR as NULL (this does not apply to CHAR). So, in the first scenario we compare against NULL.
Hello Just a thought for this we can use Dynamic sql too. If you may try this approach. Hope it helps.
CREATE OR REPLACE PROCEDURE SPS_TEST_OUT(
p_input_in IN VARCHAR2
)
AS
lv_sql LONG;
lv_where VARCHAR2(100);
BEGIN
lv_where:= CASE WHEN p_input_in IS NULL OR p_input_in = '' THEN
''
ELSE
' AND COLUMN1 LIKE '''||p_input_in||'''%'
END;
lv_sql:='SELECT * FROM TABLE
WHERE 1 = 1
' ||lv_where;
dbms_output.put_line(lv_sql);
END;

select from table where #variable in(table column)

could u please correct this sqlserver query :
select * from messages where #DepartID In(MsgTo)
#DepartID is a session variable that contains the Department ID.
MsgTo is a column in messages table that contains list of values , ex. : '12','10','13','25' .. etc
i used this code :
cmd.CommandText = "select * from messages where #DepartID IN(MsgTo)"
cmd.Parameters.AddWithValue("#DepartID ", session("DepartID")) ' = 12 for example
Dim da As New SqlDataAdapter(cmd)
Dim dt As New DataTable
da.Fill(dt)
lbmsg.text = dt.Rows.Count.ToString ' returns 0 rows
sorry for my poor english
I think you're just having some syntax trouble. Have you declared the #DepartID variable in SQL? You need to make a comparison to an existing column in your WHERE clause. Like:
SELECT [ColumnName]
FROM [Table]
WHERE [ColumnName] = Value
If your department ID is a text-type column in SQL, you'll have to use single quotes on your input. You can use single quotes anyways in integers like IDs when you query them with an "IN" statement and it will work anyways. Try this:
SELECT *
FROM [messages]
WHERE [MsgTo] = #DepartID
So if you replace your #DepartID variable out with your value and then execute the statement, it will return all information for each row where your [MsgTo] column equals your #DepartID.
If you are passing multiple #DepartIDs, then you would have to pass a comma-delimited text list to the "IN" clause with your variable like the example below:
SELECT *
FROM [messages]
WHERE [MsgTo] IN ('1','5','3','12','30')
--Example where #DepartID = '1','5','3','12','30'
I'm not sure what language you're using to execute the SQL, but if this doesn't work, try encapsulating your SQL statement within an EXEC() like below:
EXEC(
SELECT *
FROM [messages]
WHERE [MsgTo] = #DepartID
)
If your MsgTo column contains a string list of values and you want to search through it for a single #DepartID, then use this code:
DECLARE #DepartID as INT; SET #DepartID = 12; --Hard coded example
SELECT *
FROM [messages]
WHERE [MsgTo] LIKE ('%,'''+#DepartID+''',%')

SQL query with column name obtained from another table SQL Server 2012

trying to run the query
select * from customers, TablesList where TablesList.TableName+'ID' =
10 and tableslist.tableid= 123
where the column name obtained from another table. I get the following error
Msg 245, Level 16, State 1, Line 1 Conversion failed when converting
the nvarchar value 'CustomersID' to data type int.
I know I can do something like Select * from customers where customersID = 10
But trying to create CustomersID column name dynamically from another table. The intent it to have TablesList.TableName+'ID' give me CustomersID string that I can use to equate to 10.
My guess is that the value for Tablelist.TableName is Customer so when you do + 'ID' it results in 'CustomerID'. 'CustomerID' is the VALUE that is returned and not the FIELD NAME that gets compared to 10.
Hence when sqlserver try to convert 'CustomerID' to 10 you get an error message telling you that it's not an integer Value.
As far as I know you cannot get a "field name" from a field value directly trough SQL, for that you'd need to create a stored proc or some kind of programming language to build the query dynamically
TablesList.TableName+'ID' generates the string 'CustomersID'. You get the error because your comparison is actually made like this:
'CustomersID' = 10 -- The comparison NVARCHAR = INT produces the error
What i think you're trying to achieve requires dynamic SQL.
The problem with what you have is that your where clause is checking if the value 'CustomerID' is equal to 10. It isn't (and can't) use that string as a column name in that context. You need to use dynamic sql.
Dynamic SQL is where you build up a string which contains the SQL you ulitmately want to run. So as an example, you could do something like this:
declare #sql varchar(max)
set #sql = 'select * from customers where ' + (select top 1 TableName from TableList where tableId = 123) + 'ID = 10'
EXEC(#sql)
This sets the #sql variable to select * from customers where customerID = 10 then runs that statement.
Use Concat:
select * from customers, TablesList where Concat('TablesList.TableName','ID') =
10 and tableslist.tableid= 123