I have developing the MVC application for generating the report. I have provided many search option like below
Customer id
Customer name
Customer E-mail
State
Country
User 1:
If the some user will give inputs to only some Values like
Customer id = 1
Customer name = A
By default other parameters are passed as null to the stored procedure.
Customer E-mail
State
Country
User 2:
If the some user will give inputs to only some values like
Customer E-mail=xtz#gmail.com
By default other parameters are passed as null to the stored procedure.
Customer id
Customer name
State
Country
How can i use the where clause in the SQL query in the stored procedure. Can we do it like below
string qry = select * from table_name where status != d
if (#customerID!=null)
qry = qry + "and customer_id=#customerID"
if (#customerName!=null)
qry = qry + "and customer_name=#customerName"
Please let me the best approach on this.
Thanks,
Velu
If you are creating dynamic SQL then you can do just like you are above:
DECLARE #SQL NVARCHAR(MAX)
SELECT #SQL = 'SELECT * FROM TABLE '
if (#customerID IS NOT NULL)
SQL = SQL + " AND customer_id = #customerID"
Or another option is to handle it like
SELECT *
FROM TABLE
WHERE (#customerID IS NULL OR customer_id = #customerID)
I prefer the second as it is utilizing parametrized variable. First example needs to take into consideration malicious input far more intensely.
You could do dynamic SQL, but a simpler method is:
WHERE (ISNULL(#param1,1) = 1 OR [col1] = #param1)
AND (ISNULL(#param2,1) = 1 OR [col2] = #param2)
AND ...
you'll have to pass all the variables as parameters into the SP and then do your logic in there.
SqlCommand cmd = new SqlCommand("STORED_PROC_NAME", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#CustomerID", custId));
var rdr = cmd.ExecuteReader();
Related
If any, what is the difference between the following ways passing parameters.
SQLStr = "SELECT * FROM TABLE_NAME WHERE ID = ? "
command = new oleDbCommand(SQLStr, conn)
Command.Parameters.AddWithValue("#ID", Request.Querystring("ID"))
Vs.
SQLStr = "SELECT * FROM TABLE_NAME WHERE ID = #ID "
Command = new oleDbCommand(SQLStr, conn)
Command.Parameters.AddWithValue("#ID", Request.Querystring("ID"))
Maybe not in this example but could these two methods have different meanings? Perhaps when I need to pass the same value twice and I would be tempted to use the same variable name?
Thanks.
OleDbCommand does not support named parameters. Even if you use named parameter with # in your current query, their order will only matter. Currently you have only one parameter so you won't see the difference.
See: OleDbCommand.Parameters Property
The OLE DB .NET Provider does not support named parameters for passing
parameters to an SQL statement or a stored procedure called by an
OleDbCommand when CommandType is set to Text. In this case, the
question mark (?) placeholder must be used. For example:
SELECT * FROM Customers WHERE CustomerID = ?
Therefore, the order in which OleDbParameter objects are added to
the OleDbParameterCollection must directly correspond to the position
of the question mark placeholder for the parameter in the command
text.
Consider the following examples with multiple parameters:
SQLStr = "SELECT * FROM TABLE_NAME WHERE ID = #ID AND NAME = #Name";
Command = new oleDbCommand(SQLStr, conn);
Command.Parameters.AddWithValue("#Name", "ABC");
Command.Parameters.AddWithValue("#ID", Request.Querystring("ID")); //'A1'
Since #Name is added before #ID in the parameter collection, the query would look like :
SELECT * FROM TABLE_NAME WHERE ID = 'ABC' AND NAME = 'A1`; //assuming ID is A1
Note that ID got the value of NAME parameter and so as NAME got the value of ID, which is wrong.
I want to insert a record to a table called Payment which has column ID as the primary key(Auto Increment) and then I want to get that ID to use in a WHERE clause of another update statement.
var insertSatement = #"BEGIN INSERT INTO Payment (payment_type, reference, payment_date, total_records, total_amount) VALUES(#type, #reference, #date, #totalRecords, #totalAmount ) ";
var updateStatement = #"UPDATE SalaryTrans SET payment_id = (SELECT TOP 1 id FROM Payment ORDER BY Payment.id) WHERE SalaryTrans.id = #paramID ";
These two statements could not be merged as the update is going to update multiple rows. It will update all matching rows of the SalaryTrans table. So I'm using a foreach loop.
//open connection, add parameters
sqlCommand.CommandText = insertStatement;
sqlCommand.ExecuteNonQuery(); // This inserts...
foreach(PaymentInfo p in paymentList)
{
paramID.value = p.id;
sqlCommand.CommandText = updateStatement;
sqlCommand.ExecuteNonQuery();
}
In the loop each time "SELECT TOP 1 id..." is also executed. To avoid it, is there a way to use SCOPE_IDENTITY() to get the last updated ID from Payment table and use it in the loop?
Would there be a difference if I change update statement as follows in this context (performance wise) ?
DECLARE #ID INT = (SELECT TOP 1 id FROM Payment ORDER BY Payment.id)
UPDATE SalaryTrans SET payment_id = #ID WHERE SalaryTrans.id = 1
Or else should I separate this SELECT from the UPDATE to keep it outside the loop?
NOTE : My main concentration here is the performance factor.
What you can also try is, change your statement like below
var insertSatement = #"BEGIN INSERT INTO Payment (payment_type, reference, payment_date, total_records, total_amount) VALUES(#type, #reference, #date, #totalRecords, #totalAmount ); SELECT CAST(scope_identity() AS int) ";
Then in your excecute non query get the return value
sqlCommand.CommandText = insertStatement;
int id = (int) sqlCommand.ExecuteScalar(); // This inserts...
You can use the id in the loop
You can use SCOPE_IDENTITY
It will contain the latest value of the identity column from the newly inserted row
http://msdn.microsoft.com/en-us/library/ms190315.aspx
I have a stored procedure that updates my table data.
update tbl_duty
set Name = #DName,
Necessity = #DNecessity,
Payment = #DPayment,
[Estimation Time] = #DEstimationTime,
Term = #DTerm,
[Description] = #DDescription
where
Id = "what can I put here"
but I don't now how get the ID of column to update because it generated itself (identity column)
Anyone can help me?
Do we have something like GETIDENTITY(column name)?
Do you want something like this?
update tbl_duty
set Name = #DName,
Necessity = #DNecessity,
Payment = #DPayment,
[Estimation Time] = #DEstimationTime,
Term = #DTerm,
[Description] = #DDescription
where id = (select max(id) from tbl_duty);
This seems very dangerous. Why wouldn't you insert the records with the right values in the first place?
I have been tasked with updating a stored procedure and I'm trying to figure out the most efficient way of performing the select. Here is the current code, vaultID and clientID are input parameters:
SELECT
#siteID = Site.siteID,
#siteGroupID = Site.siteGroupID,
#customerID = Customer.customerID
FROM
Customer
INNER JOIN
Site ON Customer.siteID = Site.siteID
WHERE
Site.phoneNumberIVR = #vaultID
AND Site.production = 1
AND Customer.clientID = #clientID
The update I'm working on has to do with the #clientID variable. If a record has a specific #siteGroupID, the clientID needs to be passed in as it was received. If the record has a different type of #siteGroupID, the #clientID variable needs to be appended with a specific prefix. That prefix is also going to be stored on the site table.
I realize I can make a call to the site table initially to get the prefix, and then modify the #clientID variable, but I'm trying to figure out if there is a way to do this with just one call. I've been trying different case statements but I'm not sure this is even feasible.
If I understand your issue correctly, then you should be able to throw a CASE in your SELECT with your condition to do the appending:
SELECT
#siteID = Site.siteID,
#siteGroupID = Site.siteGroupID,
#customerID = Customer.customerID,
#clientID =
CASE
WHEN Site.siteGroupID = 1234 THEN Site.Prefix + #clientID
ELSE #clientID
END
FROM
Customer
inner join Site on Customer.siteID = Site.siteID
WHERE
Site.phoneNumberIVR = #vaultID
and Site.production = 1
and Customer.clientID = #clientID
Of course, depending on the datatypes of #clientID and Site.Prefix, you might have to do something other than a simple + to do the appending. For example if both were integer datatypes, you can append then with some CONVERT calls:
#clientID = CONVERT(integer, CONVERT(varchar, Site.Prefix) + CONVERT(varchar, #clientID))
It is very simple question.
I am trying to return a table from a stored procedure, like
select * from emp where id=#id
I want to return this query result as a table. I have to do this through a stored procedure.
Where is your problem??
For the stored procedure, just create:
CREATE PROCEDURE dbo.ReadEmployees #EmpID INT
AS
SELECT * -- I would *strongly* recommend specifying the columns EXPLICITLY
FROM dbo.Emp
WHERE ID = #EmpID
That's all there is.
From your ASP.NET application, just create a SqlConnection and a SqlCommand (don't forget to set the CommandType = CommandType.StoredProcedure)
DataTable tblEmployees = new DataTable();
using(SqlConnection _con = new SqlConnection("your-connection-string-here"))
using(SqlCommand _cmd = new SqlCommand("ReadEmployees", _con))
{
_cmd.CommandType = CommandType.StoredProcedure;
_cmd.Parameters.Add(new SqlParameter("#EmpID", SqlDbType.Int));
_cmd.Parameters["#EmpID"].Value = 42;
SqlDataAdapter _dap = new SqlDataAdapter(_cmd);
_dap.Fill(tblEmployees);
}
YourGridView.DataSource = tblEmployees;
YourGridView.DataBind();
and then fill e.g. a DataTable with that data and bind it to e.g. a GridView.
It's VERY important to include:
SET NOCOUNT ON;
into SP, In First line,
if you do INSERT in SP, the END SELECT can't return values.
THEN, in vb60 you can:
SET RS = CN.EXECUTE(SQL)
OR:
RS.OPEN CN, RS, SQL
In SQL Server 2008 you can use
http://www.sommarskog.se/share_data.html#tableparam
or else simple and same as common execution
CREATE PROCEDURE OrderSummary #MaxQuantity INT OUTPUT AS
SELECT Ord.EmployeeID, SummSales = SUM(OrDet.UnitPrice * OrDet.Quantity)
FROM Orders AS Ord
JOIN [Order Details] AS OrDet ON (Ord.OrderID = OrDet.OrderID)
GROUP BY Ord.EmployeeID
ORDER BY Ord.EmployeeID
SELECT #MaxQuantity = MAX(Quantity) FROM [Order Details]
RETURN (SELECT SUM(Quantity) FROM [Order Details])
GO
I hopes its help to you