How to read the values in SQL - sql

I am tying to read the values in SQl.
I am creating one purchase order If suppose any body has updated the price for the inventory then I am first checking that price is available or not.
If that price is not available then I am First Inserting that price into the datbase & then map new price with the inventory.
I have already achieved this functionality but I have wrote five inline query for this now i need to
change the code & replace with the single stored procedure. & how I can write the logic into the SQL
Here is my code with the explanation
//Checking that Buying Price Is Exist or not
//string CheckingIBM = "select * from RS_Inventory_Buying_Master where buying_price ='" + UpdatedPrice + "'";
//cm.TableConnect(CheckingIBM);
//If Buying Price is Exist then Update PIIM table with new buying_product_id
if (cmIS_Price_Exist.rs.Read())
{
//If Buying Price is Exist then Update PIIM table with new buying_product_id
common cm1 = new common();
string BuyingProductId = cmIS_Price_Exist.rs["buying_product_id"].ToString();
string UpdatePIIM = "update RS_Purchase_Invoice_Info_Master set buying_product_id = '" + BuyingProductId + "', qty = '" + UpdatedQuantity + "',tax_id ='" + TaxDetails + "',picreated = 1 where purchase_order_no = '" + PO + "' and product_id = '" + ProductId + "'";
cm1.TableInsert(UpdatePIIM);
cm1.con.Close();
}
//If Buying Price does not Exist then first Insert the price & then Update the other tables
else
{
//If Price is not exist then firsrt insert the price
common cm2 = new common();
string InsertBuyingPrice = "insert into RS_Inventory_Buying_Master (buying_price,latest) values ('" + UpdatedPrice + "','0')";
cm2.TableInsert(InsertBuyingPrice);
cm2.con.Close();
//After inserting the price find the buying product Id of that price
common cm3 = new common();
string FindingUpdatedPrice = "select * from RS_Inventory_Buying_Master where buying_price ='" + UpdatedPrice + "'";
cm3.TableConnect(FindingUpdatedPrice);
//Now finallly after finding the buying price id by using the inserted Price. Now update the buying product id of PIIM
if (cm3.rs.Read())
{
string BuyingProductId = cm3.rs["buying_product_id"].ToString();
//Now finallly after finding the buying price id. Now update the buying product id of PIIM
common cm4 = new common();
string UpdatePIIM = "update RS_Purchase_Invoice_Info_Master set buying_product_id = '" + BuyingProductId + "', qty = '" + UpdatedQuantity + "',tax_id ='" + TaxDetails + "',picreated = 1 where purchase_order_no = '" + PO + "' and product_id = '" + ProductId + "'";
cm4.TableInsert(UpdatePIIM);
cm4.con.Close();
}
cm3.con.Close();
}
Any suggesion will be appreciated.

declare #BuyingProductId varchar(50)
set #BuyingProductId = (select isnull(buying_product_id, '') from RS_Inventory_Buying_Master where buying_price = #UpdatedPrice)
if(#BuyingProductId <> '')
begin
--your update query
update RS_Purchase_Invoice_Info_Master set buying_product_id = #BuyingProductId ,
qty = #UpdatedQuantity ,tax_id = #TaxDetails ,picreated = 1
where purchase_order_no = #PO
and product_id = #ProductId ;
end
else
begin
--your insert query
insert into RS_Inventory_Buying_Master (buying_price,latest)
values (#UpdatedPrice,'0')
set #BuyingProductId = (SELECT ##IDENTITY)
update RS_Purchase_Invoice_Info_Master set buying_product_id = #BuyingProductId ,
qty = #UpdatedQuantity ,tax_id = #TaxDetails ,picreated = 1
where purchase_order_no = #PO
and product_id = #ProductId ;
end
Check with this query. Please make sure to create new sp and provide all the value like #UpdatedQuantity etc.

Related

Dapper query, combining attributes to use with pagination

I have that query that shows all my Boats, but I would just like to show the active boats.
public Pagination<Boats> GetAll(string name , int pageSize, int pageNumber)
{
var cn = Db.Database.Connection;
var sql = #"SELECT * FROM Boats" +
"WHERE (#Name IS NULL OR Name LIKE #Name + '%')" +
"ORDER BY [Name ] " +
"OFFSET " + pageSize * (pageNumber - 1) + " ROWS " +
"FETCH NEXT " + pageSize + " ROWS ONLY " +
" " +
"SELECT COUNT(Id) FROM Boats" +
"WHERE (#Name IS NULL OR Name LIKE #Name + '%')";
var multi = cn.QueryMultiple(sql, new { Name = name });
var boats= multi.Read<Boats >();
var total = multi.Read<int>().FirstOrDefault();
var paginationList= new Pagination<Boats>()
{
List = boats,
Count = total
};
return paginationList;
}
I have the active and excluded attributes in the table, so I tried to show only the boats that were active, but with this query, it keeps returning all records from the boat table, like frist one
var sql = #"SELECT * FROM Boats " +
"WHERE (#Name IS NULL OR Name LIKE #Name + '%' AND Active=1 AND Excluded=0)" +
"ORDER BY [Name] " +
"OFFSET " + pageSize * (pageNumber - 1) + " ROWS " +
"FETCH NEXT " + pageSize + " ROWS ONLY " +
" " +
"SELECT COUNT(Id) FROM Boats " +
"WHERE (#Name IS NULL OR Name LIKE #Name + '%' AND Active=1 AND Excluded=0)";
Any Ideas how can I combine the Name attribute with the Active and Excluded attributes?
Remove it from the parenthesis:
"WHERE (#Name IS NULL OR Name LIKE #Name + '%') AND Active=1 AND Excluded=0"

update/assign a user an empID in Users table

I want to update/assign a user an empID in Users table. My Update below update all rows/users with the empID and not just the selected user(cbArea.Text).
string update = "Update Users set First= '" + this.txtFirst.Text + "', empID =(SELECT DISTINCT ID from Employer where area= '" + this.cbArea.Text + "') WHERE First= '" + this.txtFirst.Text + "'" ;
First= '" + this.txtFirst.Text already in WHERE clause. When removed from set it works fine.

SQLiteDatabase select with dynamic number of conditions

I am new to databases, so it might be it is very easy.
I have the following database structure:
Table products
Table filters (could contain something like)
Color blue
Color black
Color red
Size small
Brand X
Table relation (has only product id and filter id)
Lets say I want to obtain all products that are black or red and are small, I wrote the following query:
SELECT products.name FROM products
JOIN pfrelation ON
((pfrelation.filter_id=18) AND (pfrelation.filter_id=11 OR pfrelation.filter_id=13) AND products.id=pfrelation.product_id)
In the the example above 11 and 13 represent black and red, while 18 is the id for small. As you might suspect the above query has no results (the id can not be both 18 and 11/13). How can I write the select in order to dynamically add any combination of filters? How can I rewrite the query in the example above?
Thank you
you can achieve this with Dynamic Query.
I don't much know about PostgreSql, but I know SQL Server, so I am giving a example to do same.
Here is SQLFiddel Demo
Create table Product(pid int,name varchar(10),color varchar(10),brand varchar(10),size varchar(10));
insert into product values(1,'ABC','red','X','small');
create table pfrelation(pid int,fid int,relation varchar(100));
insert into pfrelation values(1,10,'Color=''blue''');
insert into pfrelation values(1,11,'Color=''black''');
insert into pfrelation values(1,13,'Color=''red''');
insert into pfrelation values(1,18,'size=''small''');
insert into pfrelation values(1,20,'brand=''X''');
Declare #sql varchar(200)
select #sql = ((select 'pr.' + relation from pfrelation where fid = 18)
+ ' and (' +
(select 'pr.' + relation from pfrelation where fid = 11)
+ ' or ' +
(select 'pr.' + relation from pfrelation where fid = 13)
+ ') and pr.pid=pf.pid' )
select #sql
print('select * from Product pr,pfrelation pf where '+#sql)
exec('select * from Product pr,pfrelation pf where '+#sql)
I build the query dynamically this way:
public ArrayList<Products> getFilteredOnlinePictures( Hashtable<String, List<String>> filters,..)
{
SQLiteDatabase db = getWritableDatabase();
// create query conditions
StringBuffer filtersQuery = new StringBuffer();
for (String key: Collections.list(filters.keys()))
{
List<String> filtersValues = filters.get(key);
if (filtersQuery.length() > 0)
filtersQuery.append(" INTERSECT ");
filtersQuery.append("SELECT " + TABLE_PFRELATIONS + "." + COLUMN_PRODUCT_ID
+ " FROM " + TABLE_PFRELATIONS + " WHERE " + TABLE_PFRELATIONS + "."
+ COLUMN_FILTER_ID + " IN (");
for (String value: filtersValues)
{
long filterID = getIDForFilter(db, key, value);
filtersQuery.append(filterID);
if (filtersValues.indexOf(value) == (filtersValues.size() - 1))
{
// this is the last value
filtersQuery.append(")");
}
else
{
// there are more values
filtersQuery.append(",");
}
}
}
if (filtersQuery.length() > 0)
{
filtersQuery.append(")");
filtersQuery.insert(0, " WHERE " + TABLE_PRODUCTS + ".id" + " IN (");
}
String sql = "SELECT " + TABLE_PRODUCTS + "." + COLUMN_NAME + " FROM " + TABLE_PRODUCTS + filtersQuery.toString();
Cursor c = db.rawQuery(sql, null); ...
The query given as an example will be:
SELECT products.name FROM products
WHERE products.id IN (
SELECT pfrelation.product_id FROM pfrelation WHERE pfrelation.filter_id IN (18)
INTERSECT
SELECT pfrelation.product_id FROM pfrelation WHERE pfrelation.filter_id IN (11,13)
)
This way I could have any filter with any number of values.

Can these two SQL statements be made into one? Changing multiple indices with two constraints

I have a form that users can use to edit data in my database. The database is structured like this:
If a user wants to edit both a FAVE_COLOR and a FAVE_FOOD, how would I go about doing that in my SQL statement? I can think of this, but is there a way to do this in one statement?
string sql1 = "UPDATE MYTABLE " +
"SET PROP_VALUE = '" + form["color"] + "' " +
"WHERE ID = " + form["id"] + " " +
"AND PROP_NAME = 'FAVE_COLOR'"
string sql2 = "UPDATE MYTABLE " +
"SET PROP_VALUE = '" + form["food"] + "' " +
"WHERE ID = " + form["id"] + " " +
"AND PROP_NAME = 'FAVE_FOOD'"
string sql = "UPDATE MYTABLE " +
"SET PROP_VALUE = CASE " +
"WHEN PROP_NAME = 'FAVE_COLOR' THEN '" + form["color"] + "' " +
"WHEN PROP_NAME = 'FAVE_FOOD' THEN '" + form["food"] + "' " +
"END " +
"WHERE ID = " + form["id"] + " " +
"AND PROP_NAME IN ('FAVE_COLOR', 'FAVE_FOOD')"
But beware of SQL injection! You really should be using prepared statements, into which you pass your variables as parameters that do not get evaluated for SQL. If you don't know what I'm talking about, or how to fix it, read the story of Bobby Tables.
You can use case statements:
UPDATE MYTABLE
SET PROP_VALUE = (
CASE favefood
WHEN PROP_NAME = 'FAVE_FOOD'
THEN 'PIZZA'
CASE favecolor
WHEN PROP_NAME = 'FAVE_COLOR'
THEN 'BLUE'
WHERE ID = #myIdValue
For MS SQL Server you can use an UPDATE FROM which will update two properties at the same time, like this:
CREATE TABLE MYTABLE (
ID INT,
PROP_NAME VARCHAR(20),
PROP_VALUE VARCHAR(20));
go
INSERT INTO MYTABLE VALUES (1, 'A','B')
go
INSERT INTO MYTABLE VALUES (1, 'C', 'D')
go
UPDATE MYTABLE
SET PROP_VALUE = X.PROP_VALUE
FROM MYTABLE MT JOIN (
SELECT 'A' AS PROP_NAME, 'F' AS PROP_VALUE
UNION
SELECT 'C' AS PROP_NAME, 'G' AS PROP_VALUE) AS X ON MT.PROP_NAME = X.PROP_NAME
WHERE ID = 1
For other SQL DB server the solution should be similar if not identical.

Is this UPDATE table statement correct in an msdn topic

I have seen this type of UPDATE statement (just like insert statement) in the following msdn topic:
http://msdn.microsoft.com/en-us/library/aa0416cz.aspx#Y2461
UPDATE statement:-
adapter.UpdateCommand = New SqlCommand("UPDATE Customers " &
"(CustomerID, CompanyName) VALUES(#CustomerID, #CompanyName) " & _
"WHERE CustomerID = #oldCustomerID AND CompanyName = " &
"#oldCompanyName", connection)
Is this statement correct or not?
I have tried executing it and it is giving syntax errors.
No, it should be:
UPDATE Customers
SET
CustomerID = #CustomerID,
CompanyName = #CompanyName
WHERE
CustomerID = #oldCustomerID AND
CompanyName = #oldCompanyName
Or to be complete with your sample code, it should be:
adapter.UpdateCommand = New SqlCommand("UPDATE Customers SET CustomerID = #CustomerID, CompanyName = #CompanyName WHERE CustomerID = #oldCustomerID AND CompanyName = #oldCompanyName", connection)
Here is another reference for you and this situation: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldataadapter.updatecommand.aspx
That SQL appears to be correct for an INSERT INTO but not for an UPDATE It should read:
adapter.UpdateCommand = New SqlCommand("UPDATE Customers" & _
" SET CustomerID = #CustomerID, CompanyName = #CompanyName)" & _
" WHERE CustomerID = #oldCustomerID AND CompanyName =" & _
" #oldCompanyName", connection)
That SQL is what one would call paramaterized, so that makes this code (lower in the snippet) very important:
adapter.UpdateCommand.Parameters.Add( _
"#CustomerID", SqlDbType.NChar, 5, "CustomerID")
adapter.UpdateCommand.Parameters.Add( _
"#CompanyName", SqlDbType.NVarChar, 30, "CompanyName")
' Pass the original values to the WHERE clause parameters.
Dim parameter As SqlParameter = dataSet.UpdateCommand.Parameters.Add( _
"#oldCustomerID", SqlDbType.NChar, 5, "CustomerID")
parameter.SourceVersion = DataRowVersion.Original
parameter = adapter.UpdateCommand.Parameters.Add( _
"#oldCompanyName", SqlDbType.NVarChar, 30, "CompanyName")
parameter.SourceVersion = DataRowVersion.Original
As far as I can see the syntax is not valid. The following gives Incorrect syntax near '('.
I suggest changing it as per Dan's answer.
CREATE TABLE Customers
(
CustomerID INT,
CompanyName VARCHAR(10)
)
DECLARE
#CustomerID INT,
#CompanyName VARCHAR(10),
#oldCustomerID INT,
#oldCompanyName VARCHAR(10)
UPDATE Customers (CustomerID, CompanyName)
VALUES(#CustomerID, #CompanyName)
WHERE CustomerID = #oldCustomerID AND CompanyName = #oldCompanyName