INSERT with SELECT DISTINCT and another field included? - c#

I have a products table and each product have a category field (this is not up to me to change and I need to read the data from it as it is), from the product table I wanted to update a category table with unique categories only (I also use a IFNULL to deal with empty categories), this is what I have so far that works:
string query = "INSERT INTO categories (name)
SELECT DISTINCT(IFNULL(category, \"Uncategorized\")) AS category_name
FROM products
WHERE NOT EXISTS (
SELECT name FROM categories
WHERE name = category_name)";
With the above query I am able to update the categories with unique category fields and every time I need to run it, it will add only categories that does not exist to the table.
But besides the above I also need to include a profile id with each category inserted something like this, which does not work:
string query = "INSERT INTO categories (profile_id, name)
SELECT " + profileId.ToString() + ",
DISTINCT(IFNULL(category, \"Uncategorized\")) AS category_name
FROM products
WHERE NOT EXISTS (
SELECT name FROM categories
WHERE name = category_name
AND profile_id = #profileId)";
Is there a way I could acomplish this with a query ?
The above gives me a message:
SQLite error near "DISTINCT": syntax error
SqliteMan error:
Query Error: near "DISTINCT": syntax error Unable to execute statement
Let me know if I havent been clear and what should I be more clear about.

You are using the DISTINCT keyword incorrectly: it is not a function. Try instead:
"INSERT INTO categories (profile_id, name)
SELECT DISTINCT '"+profileId.ToString()+"', IFNULL(category, 'Uncategorized')
FROM products
WHERE category_name NOT IN (
SELECT name FROM categories WHERE profile_id = "'+profileId.ToString()+"'
)
"
One assumes that profileId.ToString() is guaranteed to be safe from SQL injection, or else you would be escaping it/passing it as a parameter to a prepared statement?

Related

Npgsql 5 a single select and multiple arguments

I use Npqsql 5. Is there any way to retrieve values for many different arguments using a single select?
For example I want to run:
"select value from table where id=#id1"
"select value from table where id=#id4"
"select value from table where id=#id12"
but as a single query in order to optimize.
Couple of options that come to mind:
select value from table where id = #id1 or id = #id4 or id = #id12
or
select value from table where id in (#id1, #id4, #id12)

Issue Related to where clause in SQL Server

I have a table name Students having (studentId, StudentName,Address,PhoneNo)
i have provided a filter for user to select only StudentId from Combobox to get the details of Students... and generate Report.
I have written following Query to get student Detail :
(select * from Students where StudentId = stdId)
Here stdId is a Parameter that i pass from code
It works fine if i select single studentId.... But in user selection Comobobox i have also provided "ALL" if user Select All from combobox i want to display details of all student
So what should I pass in stdId if user selects All ?
I used inline Query in C# (not using SQL Stored Procedure)
You can do it like this .
SELECT * from Students s
WHERE s.studentId = ISNULL(#StudentId,s.studentId)
When "All" is selected in combo box pass null in your #studentid parameter. If you can not pass null in parameter then pass -1 or anything which can not be contain in you combox option and do it like this:(if -1= All)
SELECT * from Students s
WHERE s.studentId = #StudentId or #StudentId=-1
You can also try the answer given by Curt.
If user selects all, pass NULL to #StudentId and change your query to:
select *
from Students
where (StudentId=#StudentId OR #StudentId IS NULL)
In your stored procedure header, change the definition of #StudentId so that it can be passed as NULL.
ALTER PROCEDURE dbo.WhateverYourProcedureIsCalled( #StudentId int = null )
Then change your WHERE clause as follows
...
SELECT * from Students
WHERE #StudentId IS NULL OR StudentId = #StudentId
From your code, if ALL is passed, you can omit the part where you set the value of the #StudentId parameter. SQL Server will use the default if not passed.
If the where clause is included in the query you also need to supply a valid parameter value and it is therefore not possible to get all students when the where clause is included.
You need to differentiate your query based on the value selected in the combobox. You can do something like the following.
int studentId = 0;
//Where selectedValue comes from your combobox
Int32.TryParse(selectedValue, out studentId);
var query = "select * from Students";
if (studentId > 0)
{
query = query + " where StudentId = #StudentId";
//Remember to add studentId as parameter value
}

How to get Sum from two tables?

i have two tables first one name is "sales" and second one name is "items"
in both tables have same columns "code" and " qtd ";
i want write MYSQL query witch i need sum(qtd) from both of tables where code is same in both of tables .
for single table i am using this
"select code,sum(qtd) from sales group by code";
Try this:
Select code, sum(qtd)
from (
select code, qtd from sales
union all
select code, qtd from items) as innerTable
group by code

Select from two tables inside an insert statement in sql

i am trying to insert a statement contains WHERE from two different tables :
the table i want to insert into is dbo.order
the other two tables are :
dbo.users. user_id.
dbo.packages. package_id.
another order field "notes".
the statement i tried is
insert into dbo.order
(customer_id,package_id,notes)
Select user_id,Package_ID
from
dbo.users,dbo.packages
where
username = 'bader' AND package_name = 'beginner','notes value here';
any suggestions ?
There's no obvious join here so you'll get the cartesian product of Bader orders and beginner packages. Not sure what the notes value should be. If its a literal you can just include it in the select clause.
insert into dbo.order
(customer_id,package_id,notes)
Select
user_id,Package_ID , 'notes value here'
from
dbo.users,dbo.packages
where
username = 'bader' AND package_name = 'beginner';
insert into dbo.order
(customer_id,package_id,notes)
Select user_id, Package_ID, 'notes value here'
from
dbo.users, dbo.packages
where
username = 'bader' AND package_name = 'beginner';

DELETE and ACCESS

Where is the error in this statement?
query = "DELETE TOP 10 FROM table WHERE field LIKE \"something*\""
I get an error on the query sytax.
Thanks.
You can't use TOP with DELETE. You must identify the rows, then delete them.
Try
query = "DELETE * from (Select TOP 10 * FROM table WHERE field LIKE \"something*\")"
While you can't directly use top with Delete, you can use it for a derived table, and then Delete from the derived table.
Try
Delete * from [tablename] where ID in (Select Top 10 ID from [Tablename] Where [Field] Like '*Condition*'
This way, you aren't looking up * (everything) in * (everything).
pay attention on quotation marks
LIKE 'something*'
If you can't do all the deletes at once, and moving to a more scalable database isn't an option, then you might try partitioning the data based on some other field and doing multiple deletes.
Let's assume you have a field called name and it's distribution is roughly even throughout the alphabet. You could do multiple deletes like this:
query0 = "DELETE FROM table WHERE field LIKE \"something*\" and name <= \"D\""
query1 = "DELETE FROM table WHERE field LIKE \"something*\" and name <= \"H\""
query2 = "DELETE FROM table WHERE field LIKE \"something*\" and name <= \"L\""
query3 = "DELETE FROM table WHERE field LIKE \"something*\" and name <= \"P\""
query4 = "DELETE FROM table WHERE field LIKE \"something*\" and name <= \"T\""
query5 = "DELETE FROM table WHERE field LIKE \"something*\" and name <= \"X\""
query6 = "DELETE FROM table WHERE field LIKE \"something*\"
You could make this work using a nested query like this...
DELETE FROM [TABLE] WHERE [Col1] = (
SELECT TOP 10 [Col1] FROM [TABLE] WHERE [criteria] ORDER BY [criteria]
);
Note in the subquery you're simply feeding a list into the main delete query by specifying what you want to delete from Col1, and the more criteria you have the fewer resources you'll need because more options for deletion will be eliminated.
To test this first Omit the DELETE FROM portion of the syntax and just run the query so you can see what you'll be feeding into your DELETE statement like this...
SELECT TOP 10 [Col1] FROM [TABLE] WHERE [criteria] ORDER BY [criteria]
Its important that you use the ORDER BY clause in case your sub query returns more than 10 results, that way you have a higher degree of control over what you're deleting.
This may or may not be possible depending on what database you're using, but you may be able to write your query something like this:
DELETE FROM TBLWHATEVER WHERE FLDWHATEVER LIKE 'something%' AND ROWNUM < 10
It depends on whether your DB has a query function like ROWNUM.

Categories