How to write the select statement in this condition? - sql-server-2008

I have a query which i am using to filter the grid
SELECT * FROM Resources
WHERE ResourceName ='" + ResourceName + "'
AND Status = '" + status + "' "
and my grid looks like this
ResourceID|ResourceName|Status
I had added the ResorceName and Status in a dropdown for filtering the grid now my problem is that in this select statement if any of the paramaters is null the data is not Binded to the grid but if I pass both the parameters it filters the grid and gives the required row or filtered row from the grid... Can anyone tell me how do I write select statement if any of the parameter is null.

Have a look it the below post on catch all queries
Catch All Examples

In terms of fixing your problem quickly, something like this would work...
Select * From Resources Where (ResourceName = '"+ ResourceName + "' OR ResourceName IS NULL) AND (Status = '" + Status +"' OR Status IS NULL)
That however is NOT an acceptable piece of code, as it is vulnerable to SQL injection. In essence, suppose the ResourceName that is passed in is
'; Drop Table Resources; --
You probably don't need me to tell you what that does.
My advice is to ALWAYS make use of SQLCommand objects in .Net - also known as "Prepared Statements" in other languages. It prevents these kind of tricks...

SELECT * FROM Resources
WHERE (ResourceName = CASE WHEN '" + ResourceName + "' IS NULL THEN ResourceName ELSE '" + ResourceName + "' END) //do same for other parameter

Related

How to Get Last Id MySQL in Scrapy?

This is the snippet of the code in my pipeline. And I want to get the last inserted ID
result = tx.execute("INSERT INTO articles(title, description, url) VALUES ('" + item['title'] + "', '" + it em['description'] + "', '" + item['url'] + "')"
)
print('#RESULT', result)
In here, the result printed 1L.
My Purpose: My article as many images, so I want to save them in a different table. By getting the last id of the article, I can use it as a foreign keys to the images table.
How do I do it? Or You have any other practical solutions?
Use tx.lastrowid to get the last row ID inserted

Conversion from type 'DBNull' to type 'Double' is not valid

In my code I understand query getting null values and it throws this error. But since my query is little complex I don't understand how do I check for null values and avoid this error. Please help me to correct this query.
SELECT (SUM(charges) + SUM(behaviour) + SUM(admission) + SUM(properInformation) + SUM(hygine) + SUM(treatment))/(count(doctorID) * 6) AverageRating, COUNT(ID) RatingCount from ratings where doctorID = '" + doctorID + "'
If you want the query to not return NULL, you can just surround the expression with IFNULL to convert a possible NULL to 0, something like;
SELECT IFNULL((SUM(charges) + SUM(behaviour) + SUM(admission) +
SUM(properInformation) + SUM(hygine) + SUM(treatment))
/(count(doctorID) * 6), 0) AverageRating,
COUNT(ID) RatingCount
FROM ratings
WHERE doctorID = '" + doctorID + "'
If you definitely know your query returning null value correctly, then you can use try-catch block as below:
Try
Dim dt As DataTable = Me.GetData("SELECT (SUM(charges) + SUM(behaviour) + SUM(admission) + SUM(properInformation)
Catch ex As Exception
MsgBox("Error while fetching data" & vbCrLf & ex.Message)
End Try

Arithmetic operations between SQL select results

Hi I need to do something like this as a part of a bigger script:
SELECT
GROUP_CONCAT(DISTINCT
CONCAT('(SUM(CASE WHEN ColumnA = "' ,ColumnA, ' "THEN 1 ELSE 0 end))/(select total
from hd_totals where ColumnA = "' ,ColumnA, ' ") AS "' ,ColumnA, ' "'))
FROM table inner join.....
The problem is that I can't do the / operation because it gives an error, even if the select output is a single value.
I don't even know how to use aliases or to store in a variable because it's a rather complex (to me) environment I'm creating here...
What about this : use CAST to have DECIMAL type, and use coalesce to prevent null values?
SELECT
GROUP_CONCAT(DISTINCT
CONCAT('COALESCE(CAST((SUM(CASE WHEN ColumnA = "' ,ColumnA, ' "THEN 1 ELSE 0 end)) AS DECIMAL(10,4)),0)/COALESCE(CAST((select total
from hd_totals where ColumnA = "' ,ColumnA, ' ") AS DECIMAL(10,4)),0.01) AS "' ,ColumnA, ' "'))
FROM table inner join.....
Note : there is an arbitrary constant 0.01 to prevent dividing by 0.
More important note : If I was you I would also add a CASE WHEN to check that you don't divide by 0.

insert statement difficulty

this is where I am getting my info from, and when I choose the address it fills in all the info
but the problem starts when I try to add a renter to the renter table after I have deleted a renter. this table no longer shows columns with all addressIDs so I am trying to insert the AddressID as well from the property table.I hope this makes sense
I cant insert pictures yet, but here is what it looks like when i chose a property, rentals
if ( ( evt.getStateChange() == java.awt.event.ItemEvent.SELECTED ) &&
( PropertyComboBox.getSelectedIndex() != 0 ) )
{
Address = ( String ) PropertyComboBox.getSelectedItem();
try {
myResultSet = myStatement.executeQuery(
"SELECT Property.Address,Property.AddressID,Property.RentAmt, Renter.RenterID, Renter.AddressID, Renter.FirstName, Renter.LastName, Renter.CellPhone, Renter.DepositPaid,Renter.DepositAmtPaid " +
"FROM Property, Renter " +
"WHERE Property.Address = '" + Address + "'" + "AND Renter.AddressID = Property.AddressID" );
if (myResultSet.next())
{
renterID = (myResultSet.getString("Renter.RenterID"));
addressID = (myResultSet.getString("Property.AddressID"));
txtRentAmt.setText(myResultSet.getString("Property.RentAmt"));
txtShowAddressID.setText(myResultSet.getString("Property.AddressID"));
txtShowRenterID.setText(myResultSet.getString("Renter.RenterID"));
txtFirstName.setText(myResultSet.getString("Renter.FirstName"));
txtLastName.setText(myResultSet.getString("Renter.LastName"));
txtCellPhone.setText(myResultSet.getString("Renter.CellPhone"));
txtDepositPaid.setText(myResultSet.getString("Renter.DepositPaid"));
txtDepositAmtPaid.setText(myResultSet.getString("Renter.DepositAmtPaid"));
if(myResultSet.getString("Renter.DepositPaid") == ("Y"))
{
txtDepositPaid.setText("Y");
}
else
{
txtDepositPaid.setText("N");
}
}
}
can someone help me with this ? I am trying to insert a new renter
from a netbeans jform into my database. The AddressID
(PK,auto-increment ) from the property table should automatically
insert into the renter table AddressID (FK, auto-increment(so I
thought)
It will insert if I use this statement but then the addressID shows as
NULL, not the AddressID from the property table, which I need. Ive
been working on this since Saturday. UGH Please help! very simple, yet
I cannot figure it out
ls_query = "INSERT INTO Renter (FirstName,LastName,CellPhone,DepositPaid,DepositAmtPaid)"
+ " VALUES (" + addressID + ",'"
+ addFirstName + "','"
+ addLastName + "','"
+ addCellPhone + "','"
+ addDepositPaid + "',"
+ addDepositAmtPaid + ")" + " WHERE Property.AddressID = " + addressID ;
INSERT plus WHERE? i guess you need UPDATE, not INSERT http://dev.mysql.com/doc/refman/5.0/en/update.html
EDIT: it's not clear, you are mixing in insert in one table with a where in another table?, just do "INSERT ... (fields) VALUES (values)" without WHERE and specify all addressID on fields.
You need to specify AddressID in the field list.
...INTO Renter (AddressID, FirstName...
Assuming that you specify all columns in the table, you can omit the field list.
You may also be more comfortable with the INSERT ... SET syntax.

SQL table accepting same names again and again database name checking

I am trying to insert the guestpass type name in table guestpasstypes and at a time it will check the database whether the database has already that name or not by using this statement:
#"INSERT INTO guestpasstypes(guestPasstype_Name)values('" + tbPassType.Text + "') where not exists (select 'guestPasstype_Name' from guestpasstypes where guestPasstype_Name = '" + tbPassType.Text + "')"
but it accepts the duplicate name too, and it does not work. Would anyone please help on this?
For SQL Server it would look like this.
insert into guestpasstypes (guestPasstype_Name)
select 'name1'
where not exists (select *
from guestpasstypes
where guestPasstype_Name = 'name1')
I think it should work for MySQL as well.
If you are on SQL Server 2008 you can use MERGE.
merge guestpasstypes as G
using (select 'name2') as S(Name)
on G.guestPasstype_Name = S.Name
when not matched then
insert (guestPasstype_Name) values (Name);
UPDATE
I think the first option could be applied to your problem like this:
#"INSERT INTO guestpasstypes(guestPasstype_Name) select '" + tbPassType.Text
+ "' where not exists (select * from guestpasstypes where guestPasstype_Name = '"
+ tbPassType.Text + "')"
If you want it to throw an error you can either :
Put a unique index on the column (the easiest and preferred way)
or
Write a stored procedure which returns an error flag. Within the procedure, you first check for a matching value and if one is found, set the error flag and return. Otherwise do the insert as normal.
Try either INSERT IGNORE or INSERT ON DUPLICATE KEY:
INSERT IGNORE INTO `guestpasstypes`(`guestPasstype_Name`) values('" + tbPassType.Text + "');
OR
INSERT INTO `guestpasstypes`(`guestPasstype_Name`)values('" + tbPassType.Text + "') ON DUPLICATE KEY UPDATE `guestPasstype_Name` = `guestPasstype_Name`;