Getting values of a column, depending values of another column - sql

I want to take all the data, (that matches from "name" column) from "barcode" column. Like this:
SELECT barcode FROM table1 where name like 'abc%'
But that doesn't work.

if you mean get barcode based on selected category value, you need to pass the selected value as SqlParameter. ex. in your OnCategoryChanged function,
string queryString =
"SELECT barcode FROM table1 where category=#category;";
using (SqlConnection connection =
new SqlConnection(connectionString))
{
var cmd = new SqlCommand(queryString, connection);
cmd.Parameters.AddWithValue("#category", comboBox1.SelectedValue);
connection.Open();
var reader = cmd.ExecuteReader();
...
// Call Close when done reading.
reader.Close();
}

If anyone would be so kind to send, I am still waiting for an answer. Considering my comments above and below. Thank you...

Related

Display the latest updated data

I have to display the data that currently being updated in the text file. The problem is, I'm using the CONVERT function for the columns that I need to display. The data that being displayed is System.Byte[]. The actual data that I need to display is a varbinary string.
-- This query is displaying the data before updating the status.
query = SELECT CONVERT(varchar(10), Start_RG, 2) AS Start_RG, CONVERT(varchar(10), End_RG, 2) AS End_RG, Status FROM RG WHERE Status = 'New';
command = new SqlCommand(query, cnn);
dR = command.ExecuteReader();
if (dR.HasRows)
{
dR.Close();
-- This is the query for updating the status to 'In Use'. I'm using the OUTPUT clause to display the data that has been update.
sql = UPDATE TOP (1) RG SET Status = 'In Use' OUTPUT deleted.Start_RG, deleted.End_RG, deleted.Status WHERE Status = 'New';
cmd= new SqlCommand(sql, cnn);
dataReader = cmd.ExecuteReader();
using (StreamWriter tw = File.AppendText(Path))
{
while (dataReader.Read())
{
tw.WriteLine("assign..\n");
tw.WriteLine("Start RG: {0}", Convert.Tostring((byte[])dataReader["Start_RG"]));
tw.WriteLine("End RG: {0}", Convert.Tostring((byte[])dataReader["End_RG"]));
}
}
}
How can I fetch the Start_RG and End_RG that currently updated the status to In Use? Any other suggestion that I can use instead of OUTPUT clause?
Whatever you are doing using OUTPUT clause is fine. For reading byte[] to string, you can use below approach. Leveraged Stackoverflow answer: https://stackoverflow.com/a/4959269/634935
tw.WriteLine("Start RG: {0}", Encoding.ASCII.GetString(((byte[])dataReader["Start_RG"])); //based on encoding, you need to choose appropriate static method
tw.WriteLine("End RG: {0}", Encoding.ASCII.GetString(((byte[])dataReader["End_RG"]));

Getting Exception in Summing the values of a column of a table in SQL using ASP.Net

I am trying to add the values of a column of a table. My table looks like this:
enter image description here
I want to add the values of months column for a specific id. My code looks like this:
public int MonthSum(int id)
{
SqlConnection connection = new SqlConnection(connectionString);
string query = "select sum(months) from PayTable where ID=#ID group by ID";
SqlCommand command = new SqlCommand(query,connection);
command.Parameters.Clear();
command.Parameters.Add("ID", SqlDbType.Int);
command.Parameters["ID"].Value = id;
connection.Open();
int total = (int)command.ExecuteScalar();
connection.Close();
return total;
}
Why I am getting exception here??
Since you don't provide more information about the exception, it's only guessing, but you may have a problem adding the parameter as "ID" instead of "#ID". I think that SqlCommand expects the name with the #.
Here some Microsoft documentation with an example very similar to what you are doing.

Can I use count(*) and AND in select sql query at same time?

SqlConnection sc = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=D:\6th sem\DNT\tutorials\application\WindowsFormsApplication2\WindowsFormsApplication2\Login.mdf;Integrated Security=True");
sc.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = sc;
//cmd.CommandText = "SELECT count(*) FROM dictionary WHERE word=#Word AND user=#Unique";
cmd.Parameters.AddWithValue("#Word", textBox_word.Text);
cmd.Parameters.AddWithValue("#Unique", frm.textUserName);
cmd.CommandText = "SELECT COUNT(*) FROM dictionary WHERE word=#Word AND user=#Unique";
int z = (int)cmd.ExecuteScalar();
MessageBox.Show(z.ToString());
if (z >= 1)
{
MessageBox.Show("word already entered in your id");
}
else
{
}
My code is always going in else part and output of above query is always 0 !!!
You should probably use Profiler to see what is being passed to your parameters, but I am highly suspicious of this line:
cmd.Parameters.AddWithValue("#Unique", frm.textUserName);
Don't you want to access the .text property of the textUserName object, the way you did with the #Word parameter?
finally found an answer...
it was problem with SQL database coloumn name user which they are not allowing i dont know the reason why but that was it in my case.
so i changed the coloumn name to user1 and it works correctly...
suggestion 1:-
Please store the values of textBox_word.Text and frm.textUserName in another values and then put here.
cmd.Parameters.AddWithValue("#Word", value1);
cmd.Parameters.AddWithValue("#Unique",value2);
If still any issue then
Suggestion 2:-
Please debug the code and check what exactly values are comming for value1 and value2

Oracle Parameters in .net sql queries - ORA-00933: SQL command not properly ended

I am trying to do create a where clause to pass as a parameter to an Oracle command and it's proving to be more difficult than I thought. What I want to do is create a big where query based off user input from our application. That where query is to be the single parameter for the statement and will have multiple AND, OR conditions in it. This code here works however isn't exactly what I require:
string conStr = "User Id=testschema;Password=pass12341;Data Source=orapdex01";
Console.WriteLine("About to connect to Database with Connection String: " + conStr);
OracleConnection con = new OracleConnection(conStr);
con.Open();
Console.WriteLine("Connected to the Database..." + Environment.NewLine + "Press enter to continue");
Console.ReadLine();
// Assume the connection is correct because it works already without the parameterization
String block = "SELECT * FROM TEMP_VIEW WHERE NAME = :1";
// set command to create anonymous PL/SQL block
OracleCommand cmd = new OracleCommand();
cmd.CommandText = block;
cmd.Connection = con;
// since execurting anonymous pl/sql blcok, setting the command type
// as text instead of stored procedure
cmd.CommandType = CommandType.Text;
// Setting Oracle Parameter
// Bind the parameter as OracleDBType.Varchar2
OracleParameter param = cmd.Parameters.Add("whereTxt", OracleDbType.Varchar2);
param.Direction = ParameterDirection.Input;
param.Value = "MY VALUE";
// Get returned values from select statement
OracleDataReader dr = cmd.ExecuteReader();
// Read the identifier for each result and display it
while (dr.Read())
{
Console.WriteLine(dr.GetValue(0));
}
Console.WriteLine("Selected successfully !");
Console.WriteLine("");
Console.WriteLine("***********************************************************");
Console.ReadKey();
If I change the lines below to be the type of result I want then I get an error "ORA-00933: SQL command not properly ended":
String block = "SELECT * FROM TEMP_VIEW :1";
...
...
param.Value = "WHERE NAME = 'MY VALUE' AND ID = 5929";
My question is how do I accomplish adding my big where query dynamically without causing this error?
Sadly there is no easy way to achieve this.
One thing you will need to understand with parameterised SQL in general is that bind parameters can only be used for values, such as strings, numbers or dates. You cannot put bits of SQL in them, such as column names or WHERE clauses.
Once the database has the SQL text, it will attempt to parse it and figure out whether it is valid, and it will do this without taking any look at the bind parameter values. It won't be able to execute the SQL without all of the values.
The SQL string SELECT * FROM TEMP_VIEW :1 can never be valid, as Oracle isn't expecting a value to immediately follow FROM TEMP_VIEW.
You will need to build up your SQL as a string and also build up the list of bind parameters at the same time. If you find that you need to add a condition on the column NAME, you add WHERE NAME = :1 to the SQL string and a parameter with name :1 and the value you wish to add. If you have a second condition to add, you append AND ID = :2 to the SQL string and a parameter with name :2.
Hopefully the following code should explain a little better:
// Initialise SQL string and parameter list.
String sql = "SELECT * FROM DUAL";
var oracleParams = new List<OracleParameter>();
// Build up SQL string and list of parameters.
// (There's only one in this somewhat simplistic example. If you have
// more than one parameter, it might be easier to start the query with
// "SELECT ... FROM some_table WHERE 1=1" and then append
// " AND some_column = :1" or similar. Don't forget to add spaces!)
sql += " WHERE DUMMY = :1";
oracleParams.Add(new OracleParameter(":1", OracleDbType.Varchar2, "X", ParameterDirection.Input));
using (var connection = new OracleConnection() { ConnectionString = "..."})
{
connection.Open();
// Create the command, setting the SQL text and the parameters.
var command = new OracleCommand(sql, connection);
command.Parameters.AddRange(oracleParams.ToArray());
using (OracleDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
// Do stuff with the data read...
}
}
}

ExecuteReader returns no results, when inspected query does

Consider the following code:
StringBuilder textResults = new StringBuilder();
using(SqlConnection connection = new SqlConnection(GetEntityConnectionString()))
{
connection.Open();
m.Connection = connection;
SqlDataReader results = m.ExecuteReader();
while (results.Read())
{
textResults.Append(String.Format("{0}", results[0]));
}
}
I used Activity Monitor within Sql Server Mgmt Studio on the database to inspect the exact query that was being sent. I then copied that query text to a query editor window within SSMS, and the query returned the expected results. However, SqlDataReader results is always empty, indicating "The enumeration returned no results."
My suspicion is that somehow the results are not being returned correctly, which makes me think there's something wrong with the code above, and not the query itself being passed.
Is there anything that would cause this in the code above? Or something I've overlooked?
EDIT:
Here is the query as indicated by the SQLCommand object:
SELECT DISTINCT StandardId,Number
FROM vStandardsAndRequirements
WHERE StandardId IN ('#param1','#param2','#param3')
ORDER BY StandardId
Here is the query as it appears in Activity Monitor:
SELECT DISTINCT StandardId,Number
FROM vStandardsAndRequirements
WHERE StandardId IN ('ABC-001-0','ABC-001-0.1','ABC-001-0')
ORDER BY StandardId
The query is working against a single view.
When I ran the second query against the database, it returned 3 rows.
The SqlDataReader indicates 0 rows.
try to use Sqldata adapter instead of sqldatreader.
StringBuilder textResults = new StringBuilder();
using (var conn = new SqlConnection(GetEntityConnectionString())))
{
using (
var cmd = new SqlCommand(
"SELECT DISTINCT StandardId,Number" +
"FROM vStandardsAndRequirements " +
"WHERE StandardId IN (#param1,#param2,#param3)" +
"ORDER BY StandardIdl"
, conn))
{
var dSet = new DataSet();
var dt = new Datatable();
var da = new SqlDataAdapter(cmd);
cmd.Parameters.Add("#param1", SqlDbType.VarChar, 50).Value = "ABC-001-0";
cmd.Parameters.Add("#param2", SqlDbType.VarChar, 50).Value = "ABC-001-0.1";
cmd.Parameters.Add("#param3", SqlDbType.VarChar, 50).Value = "ABC-001-0";
try
{
da.Fill(dSet);
dt = dSet.Tables[0];
foreach(Datarow a in dt.Rows)
{
textResults.Append(a["StandardId"].tostring()).AppendLine();
}
Messabox.Show(textResults.tostring);
}
catch (SqlException)
{
throw;
}
finally
{
if (conn.State == ConnectionState.Open) conn.Close();
}
}
}
Regards.
Are you sure it is
WHERE StandardId IN ('#param1','#param2','#param3')
instead of this?
WHERE StandardId IN (#param1,#param2,#param3)
Parameters should not be quoted, not in the SQLCommand object.
Very nice behavior I've observed
I looked for errors in code:
... dr = command.ExecuteReader() ... If dr.Read Then ...
and found that 'dr.Read' works fine, but...
when I mouseover on 'dr', to lookup for data, return values disappeared !
Check your connection string and make sure you are not connecting as a user instance.
http://msdn.microsoft.com/en-us/library/ms254504.aspx