Filler word for SQLite statement to return any and all rows using WHERE [duplicate] - sqlite

I am doing my crm project with SQLITE+FLASK. And I need a feature is let user to input the condition to filer the result.
I hope that my SQL statement can ignore the WHERE condition if the parameter is space or null.
For example, My input is "NAME", "AGE", "GENDER"
so my statement will be
SELECT *
FROM CUSTOMER
WHERE NAME = 'James' AND AGE = '25' AND GENDER = 'M'
But I hope that if user did not enter "NAME" my SQL statement can be something like the code below
SELECT *
FROM CUSTOMER
WHERE AGE = '25' AND GENDER = 'M'
I know maybe I can do this with string concat, but I hope I can do this by SQL statement.

You can do it with the OR operator for each of the columns, by checking also if the parameter value that you pass is NULL or a string with spaces:
SELECT *
FROM CUSTOMER
WHERE (NAME = :name OR TRIM(COALESCE(:name, '')) = '')
AND (AGE = :age OR TRIM(COALESCE(:age, '')) = '')
AND (GENDER = :gender OR TRIM(COALESCE(:gender, '')) = '')

You can use null condition as follows:
SELECT *
FROM CUSTOMER
WHERE (NAME = :name_input or :name_input is null)
AND (AGE = :age_input or :age_input is null)
AND (GENDER = :gender_input or :gender_input is null)

Related

Lua Recursion issue unexpected result

I'm trying to figure out why this function is ignoring the middle most table? I'm overlooking something simple I assume.
Here's the code
tbl = {
name = "first table";
tbl = {
name = "middle table";
tbl = {
name = "last table";
};
};
}
sayName = function(tbl)
print(tbl.name)
if tbl.tbl ~= nil then
for _,v in pairs(tbl.tbl) do
sayName(v)
end;
end;
end;
sayName(tbl)
Output>
first table
last table
nil
In your example, you have a recursive structure, each table have 1 name and possibly a sub-table named tbl. So, I am not clear why would one use the for loop in these conditions.
tbl = {
name = "first table",
tbl = {
name = "middle table",
tbl = {
name = "last table"
}
}
}
function PrintTable (Table)
print("# Name", Table.name)
local SubTable = Table.tbl
if SubTable then
return PrintTable(SubTable)
end
end
PrintTable(tbl)
Will return:
# Name first table
# Name middle table
# Name last table

Request rows with amount IS NULL (IS NOT NULL) cells in Sqlite3 (SELECT command)

Is it possible to create a request in Sqlite3 of the SELECT type, which will contain the condition "select a row where amount NULL (or IS NOT NULL) cells will be more (less) a certain number"?
With this query:
SELECT * FROM tablename
WHERE (col1 IS NULL) + (col2 IS NULL) + (col3 IS NULL) + .... > ?
Each of the expressions (colX IS NULL) or (colX IS NOT NULL) evaluates to 1 for true or 0 for false, so you can compare their sum to the number ? that you want.

Stored Procedures and asp.net programmability; variable or SQL

Trying to display a users Lastname, Firstname --- Website
And I need to insert a comma and space after Lastname to a GridView.
I am trying to add a CASE statement in SQL and having trouble figuring it out.
Perhaps I need to use #parameter (scalar variable?) to abstract the
memory read from CASE statement; or my syntax is wrong and I just don't
understand.
SELECT
CASE
WHEN IsNull(people_Table.firstName, '') = ''
THEN CONCAT(people_Table.lastName, ', ', people_Table.firstName)
ELSE people_Table.lastName
END as fullName,
people_Table.website
FROM
people_Table
INNER JOIN
membership_Table on people_Table.ID = membership_Table.personID
WHERE
rectype = 'Master'
AND membershipType = 'Business'
AND expirationDate > GetDate()
ORDER BY
people_Table.lastName
Getting SQL Server error:
Msg 208, Level 16, State 1, Line 1
Invalid object name 'people_Table'.
Otherwise I suppose I should use an asp databoundevent in the template.
What is better for performance and security?
SELECT ISNULL(people_Table.lastName + ', ', '')
+ ISNULL(people_Table.firstName , '') as fullName
, people_Table.website
FROM people_Table INNER JOIN membership_Table on people_Table.ID =
membership_Table.personID
WHERE rectype = 'Master'
AND membershipType = 'Business'
AND expirationDate > GetDate()
ORDER BY people_Table.lastName
OR
SELECT COALESCE(people_Table.lastName + ', ', '')
+ COALESCE(people_Table.firstName , '') as fullName
, people_Table.website
FROM people_Table INNER JOIN membership_Table on people_Table.ID =
membership_Table.personID
WHERE rectype = 'Master'
AND membershipType = 'Business'
AND expirationDate > GetDate()
ORDER BY people_Table.lastName

use ArrayList as filter in linq query "where" keyword

I have some data in an ArrayList and I would like to use that to filter my Linq query using the where clause.
My Linq code below joins two tables and then I filter them using the Where clause. Now I would like to FURTHER filter this query by using the Arraylist as a filter. So the value come from arraylist
I would like the "where" clause to take one more comparison and the value comes from an arraylist:
where rType.Field<string>("ProfSSCMName") == lbProfiles.SelectedValue && rType.Field<string>("Name") == lbHWTypes.SelectedValue && **arrayList.Tostring()**
This is the code that I am using.
Can anyone tell me how can I further filter my Linq query using the values in the arraylist?
joined = from rType in ds.Tables["HWTypes"].AsEnumerable()
join rStock in ds.Tables["Stock"].AsEnumerable()
on rType.Field<string>("ProductID") equals rStock.Field<string>("Partno")
where rType.Field<string>("ProfSSCMName") == lbProfiles.SelectedValue && rType.Field<string>("Name") == lbHWTypes.SelectedValue
select new
{
TagNumber = rStock.Field<string>("TagNumber"),
SerialNumber = rStock.Field<string>("SerialNumber"),
Partno = rStock.Field<string>("Partno"),
PartType = rStock.Field<string>("PartType"),
EcopartSubtype = rStock.Field<string>("EcopartSubtype"),
AzertyQuerty = rStock.Field<string>("Azerty/Querty"),
ProductID = rType.Field<string>("ProductID"),
Name = rType.Field<string>("Name"),
SCCMKeyboard = rType.Field<string>("SCCMKeyboard"),
DisplayName = rType.Field<string>("DisplayName"),
ProfSSCMName = rType.Field<string>("ProfSSCMName"),
TagNameDisplayName = rStock.Field<string>("TagNumber") + " " + rType.Field<string>("DisplayName")
// add the other columns you need here
};
You seem to be using Linq-To-Objects.
So you can just use contains on the arraylist
where rType.Field<string>("ProfSSCMName") == lbProfiles.SelectedValue
&& rType.Field<string>("Name") == lbHWTypes.SelectedValue
&& arrayList.Contains( rType.Field<string>("Name") )

How to get a list of column names

Is it possible to get a row with all column names of a table like this?
|id|foo|bar|age|street|address|
I don't like to use Pragma table_info(bla).
SELECT sql FROM sqlite_master
WHERE tbl_name = 'table_name' AND type = 'table'
Then parse this value with Reg Exp (it's easy) which could looks similar to this: [(.*?)]
Alternatively you can use:
PRAGMA table_info(table_name)
If you are using the command line shell to SQLite then .headers on before you perform your query. You only need to do this once in a given session.
You can use pragma related commands in sqlite like below
pragma table_info("table_name")
--Alternatively
select * from pragma_table_info("table_name")
If you require column names like id|foo|bar|age|street|address, basically your answer is in below query.
select group_concat(name,'|') from pragma_table_info("table_name")
Yes, you can achieve this by using the following commands:
sqlite> .headers on
sqlite> .mode column
The result of a select on your table will then look like:
id foo bar age street address
---------- ---------- ---------- ---------- ---------- ----------
1 val1 val2 val3 val4 val5
2 val6 val7 val8 val9 val10
This helps for HTML5 SQLite:
tx.executeSql('SELECT name, sql FROM sqlite_master WHERE type="table" AND name = "your_table_name";', [], function (tx, results) {
var columnParts = results.rows.item(0).sql.replace(/^[^\(]+\(([^\)]+)\)/g, '$1').split(','); ///// RegEx
var columnNames = [];
for(i in columnParts) {
if(typeof columnParts[i] === 'string')
columnNames.push(columnParts[i].split(" ")[0]);
}
console.log(columnNames);
///// Your code which uses the columnNames;
});
You can reuse the regex in your language to get the column names.
Shorter Alternative:
tx.executeSql('SELECT name, sql FROM sqlite_master WHERE type="table" AND name = "your_table_name";', [], function (tx, results) {
var columnNames = results.rows.item(0).sql.replace(/^[^\(]+\(([^\)]+)\)/g, '$1').replace(/ [^,]+/g, '').split(',');
console.log(columnNames);
///// Your code which uses the columnNames;
});
Use a recursive query. Given
create table t (a int, b int, c int);
Run:
with recursive
a (cid, name) as (select cid, name from pragma_table_info('t')),
b (cid, name) as (
select cid, '|' || name || '|' from a where cid = 0
union all
select a.cid, b.name || a.name || '|' from a join b on a.cid = b.cid + 1
)
select name
from b
order by cid desc
limit 1;
Alternatively, just use group_concat:
select '|' || group_concat(name, '|') || '|' from pragma_table_info('t')
Both yield:
|a|b|c|
The result set of a query in PHP offers a couple of functions allowing just that:
numCols()
columnName(int $column_number )
Example
$db = new SQLIte3('mysqlite.db');
$table = 'mytable';
$tableCol = getColName($db, $table);
for ($i=0; $i<count($tableCol); $i++){
echo "Column $i = ".$tableCol[$i]."\n";
}
function getColName($db, $table){
$qry = "SELECT * FROM $table LIMIT 1";
$result = $db->query($qry);
$nCols = $result->numCols();
for ($i = 0; $i < $ncols; $i++) {
$colName[$i] = $result->columnName($i);
}
return $colName;
}
$<?
$db = sqlite_open('mysqlitedb');
$cols = sqlite_fetch_column_types('form name'$db, SQLITE_ASSOC);
foreach ($cols as $column => $type) {
echo "Column: $column Type: $type\n";
}
Using #Tarkus's answer, here are the regexes I used in R:
getColNames <- function(conn, tableName) {
x <- dbGetQuery( conn, paste0("SELECT sql FROM sqlite_master WHERE tbl_name = '",tableName,"' AND type = 'table'") )[1,1]
x <- str_split(x,"\\n")[[1]][-1]
x <- sub("[()]","",x)
res <- gsub( '"',"",str_extract( x[1], '".+"' ) )
x <- x[-1]
x <- x[-length(x)]
res <- c( res, gsub( "\\t", "", str_extract( x, "\\t[0-9a-zA-Z_]+" ) ) )
res
}
Code is somewhat sloppy, but it appears to work.
Try this sqlite table schema parser, I implemented the sqlite table parser for parsing the table definitions in PHP.
It returns the full definitions (unique, primary key, type, precision, not null, references, table constraints... etc)
https://github.com/maghead/sqlite-parser
Easiest way to get the column names of the most recently executed SELECT is to use the cursor's description property. A Python example:
print_me = "("
for description in cursor.description:
print_me += description[0] + ", "
print(print_me[0:-2] + ')')
# Example output: (inp, output, reason, cond_cnt, loop_likely)

Resources