Test a value of multiple columns, Access SQL from Visual Studio - c#

I want to import a table from Access DB, in this table there is a column that is valued and not, when not I want to fill this column on the result table with a default value or let it empty.
I tried IsNull(col2 ,'')
Thanks in advance
MyQuery = "SELECT col1 AS col1, col2 AS myDevice";
MyQuery += " FROM table 1";
OleDbCommand cmd1 = new OleDbCommand(MyQuery, conn);
OleDbDataAdapter adapter1 = new OleDbDataAdapter(cmd1);
adapter1.Fill(table);
DB.Tables.Add(table);

In MS Access, you want the Nz() function:
Nz(col2 ,'default')
IsNull() exists in Access but it is meant to check if a value is null (and it returns a boolean value).

I solved with this:
MyQuery = "SELECT col1 AS col1, IIF(ISNULL(col2), 0, col2) AS myDevice";
Thanks

Related

SQL Server - Update table and return the Updated rows

I have a SQL Server database which has a lot of information inside.
I want to select top 50 rows in a single query (which I did, with no problem) but then I want to update a column from false to true, so next time I select I wont select the same, my code looks like this:
string Command = "UPDATE HubCommands SET [Alreadytaken] = 'true' FROM (SELECT TOP 50 [CommandId],[DeviceId],[Commandtext], [HashCommand],[UserId] FROM HubCommands) I WHERE [HubId] = '18353fe9-82fd-4ac2-a078-51c199d9072b'";
using (SqlConnection myConnection = new SqlConnection(SqlConnection))
{
using (SqlDataAdapter myDataAdapter = new SqlDataAdapter(Command, myConnection))
{
DataTable dtResult = new DataTable();
myDataAdapter.Fill(dtResult);
foreach (DataRow row in dtResult.Rows)
{
Guid CommandId, DeviceId, UserId;
Guid.TryParse(row["CommandId"].ToString(), out CommandId);
Guid.TryParse(row["DeviceId"].ToString(), out DeviceId);
Guid.TryParse(row["UserId"].ToString(), out UserId);
Console.WriteLine("CommandId" + CommandId);
}
}
}
This code does work, and it updates what I ask it to update, but I don't get nothing in the data table, its like it is always updating but not selecting.
If I do a normal select it does work and give information.
Does anyone have any idea how to update and get some data back, in a single query?
So your question is:
How can I update a table in SQL Server using C# and return the truly updated
rows as a DataTable ?
First You have multiple issues in your query.
You should use 1 and 0, not true or false. SQL-Server has a bit datatype and not a Boolean.
Second, this is how you should've constructed your query:
DECLARE #IDs TABLE
(
[CommandId] uniqueidentifier
);
INSERT INTO #IDs
SELECT [CommandId] FROM HubCommands
WHERE [HubId] = '18353fe9-82fd-4ac2-a078-51c199d9072b' AND [Alreadytaken] = 0;
UPDATE HubCommands
SET [Alreadytaken] = 1
WHERE CommandId IN
(
SELECT [CommandId] FROM #IDs
);
SELECT * FROM HubCommands
WHERE CommandId IN
(
SELECT [CommandId] FROM #IDs
);
Wrap all the above in a single string and use SqlDataReader. No need for an Adapter in you case (Since we're mixing commands unlike what the adapter usually does):
var sqlCommand = new SqlCommand(Command, myConnection);
SqlDataReader dataReader = sqlCommand.ExecuteReader();
DataTable dtResult = new DataTable();
dtResult.Load(dataReader);
I highly advise you to create a stored procedure accepting HubId as a parameter that does all the above work. It is neater and better for maintenance.

Copy Records From Access Table To Access Table

In C# I am trying to insert records from one access table to another access table, but I get the above error message. What is causing this error (OleDbException: No value given for one or more required parameters) as it is a straight Select * statement?
OleDbConnection connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=P:\\Source.mdb;");
connection.Open();
OleDbCommand command = new OleDbCommand("INSERT INTO [;DATABASE=V:\\Destination.mdb;].[table1] SELECT * FROM table1 WHERE company = 2", connection);
command.ExecuteNonQuery();
connection.Close();
EDIT --- Error in Insert Statement
OleDbConnection connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=P:\\Source.mdb;");
connection.Open();
OleDbCommand command = new OleDbCommand("INSERT INTO [;DATABASE=V:\\Destination.mdb;].[table1] (Name, Address, Phone, RepeatCustomer) SELECT Name, Address, Phone, RepeatCustomer FROM table1 WHERE company = 2", connection);
command.ExecuteNonQuery();
connection.Close();
Are the two tables identical? You'd get this error if the column order and/or types don't match. It's much better form to explicitly define the columns you want to modify:
INSERT INTO [;DATABASE=V:\\Destination.mdb;].[table1] (col1,col2) SELECT col1,col2 FROM table1 WHERE company = 2
this way, order doesn't matter, and you aren't trying to add to columns that don't exist.
I had the same issue copying to the same table. This sample of just two fields worked for me:
INSERT INTO [Orders] (CUST, PART_NUMBE) SELECT CUST, PART_NUMBE FROM [orders]
WHERE [OrderNumber]= 23979

What method can be used to specifically insert data into your C# DataGridView from SQL?

Problem:
Code works fine, however, when I launch my program my two predefined columns Course_ID and File_Count are present in my then blank dataGridView. There is also an empty default row.
Whenever I run my query, my dataGridView is getting an extra column created and an extra row created. The result from the query goes into this new third column on the first row which is weird.
See here:
http://imgur.com/UBFI8Nz
Here is my code:
string[] courses = txtBoxCourses.Text.Split(',');
SqlConnection myConnection = new SqlConnection("user id=userid;" +
"password=password;server=myserver;" +
"Trusted_Connection=no;" +
"connection timeout=30");
myConnection.Open();
SqlCommand myCommand = new SqlCommand();
SqlDataAdapter adapter = new SqlDataAdapter(myCommand);
myCommand.Connection = myConnection;
DataTable t = new DataTable();
foreach (string line in courses)
{
myCommand.CommandText = "DECLARE #CourseName varchar(80); Set #CourseName = '"+line+"' SELECT COUNT(*) FROM ( SELECT FILE_ID,PARENT_ID ,PATH_ID,FULL_PATH ,FILE_NAME FROM BBLEARN_cms_doc.dbo.XYF_URLS WHERE FULL_PATH like '/courses/'+#CourseName+'/%') as subquery;";
adapter.Fill(t);
dataGridView1.DataSource = t;
}
What I want to happen is I want to fill in the first column with the values from my string[] courses list and I want it to correspond with the result from the query in my foreach statement. For example, if I use two course IDs to query, test1 and test2 I'd prefer this:
Course_ID file_count
test1 234
test2 1478
I've looked into using the DataPropertyName property but I don't think that's it.
Try changing your select to:
SELECT #CourseName as Course_ID, COUNT(*) as File_Count FROM (
SELECT FILE_ID,PARENT_ID ,PATH_ID,FULL_PATH ,FILE_NAME FROM BBLEARN_cms_doc.dbo.XYF_URLS
WHERE FULL_PATH like '/courses/'+#CourseName+'/%') as subquery;
Your current query is returning an integer and your grid view doesn't see it attached to any of your predefined columns. Try aliasing the columns with the column name in the grid view. That should tie your sql results to your current columns.

How do I retrieve DataColumn.DefaultValue from a Sql Table?

Is there a way to determine a column's defaultvalue from the Sql Database using ado.net?
I tried using the SqlDataAdapter's FillSchema method:
using (SqlDataAdapter adapter = new SqlDataAdapter()) {
adapter.SelectCommand = myConnection.CreateCommand();
adapter.SelectCommand.CommandType = CommandType.Text;
adapter.SelectCommand.CommandText = "SELECT * FROM myTable";
DataTable table = new DataTable();
adapter.Fill(table);
adapter.FillSchema(table, SchemaType.Mapped);
}
When I inspect the DataColumns in the DataTable, I can determine if a column is an AutoIncrement, and can determine if it allows nulls using the AllowDBNull property. However, DefaultValue (for columns that I know have a default value) is always null.
I considered:
DataTable schemaTable = null;
using (SqlDataReader reader = adapter.SelectCommand.ExecuteReader(CommandBehavior.SchemaOnly)) {
schemaTable = reader.GetSchemaTable();
reader.Close();
}
but DefaultValue is not included in the schema.
So...how can I get a column's DefaultValue?
Use this query to interrogate the INFORMATION_SCHEMA for the info you're looking for:
SELECT
TABLE_NAME, COLUMN_NAME, COLUMN_DEFAULT
FROM
INFORMATION_SCHEMA.COLUMNS
WHERE
TABLE_NAME = 'your table name' AND
COLUMN_NAME = 'your column name'
Marc
Not really. This is because the default value can be determined at the time a record is inserted (like a GETDATE() or NEW_ID()). So the value cannot be determined in advance.
The COLUMN_DEFAULT column of INFORMATION_SCHEMA.COLUMNS gives you not the actual default value, but a string representation of the code SQL Server and the likes will execute to generate the default value. See http://msdn.microsoft.com/en-us/library/ms188348.aspx.
Having said that, simple constant values can easily be deduced from such an expression.

How can I know if such value exists in database? (ADO.NET)

For example, I have a table, and there is a column named 'Tags'. I want to know if value 'programming' exists in this column. How can I do this in ADO.NET?
I did this: OleDbCommand cmd = new OleDbCommand("SELECT * FROM table1 WHERE Tags='programming'", conn);
OleDbDataReader = cmd.ExecuteReader();
What should I do next?
use SELECT COUNT(*) and check the results.
(and use ExecuteScalar)
(assuming you know how to set the connection and use it)
SELECT TOP 1 1
FROM table1
WHERE Tags='programming'
better version, it is a good practice to use parameters instead of string concatenation, see sql injection
OleDbCommand cmd = new OleDbCommand("SELECT TOP 1 1
FROM table1 WHERE Tags=?", conn);
cmd.Parameters.Add("#p1", OleDbType.VarChar).Value = "Programming";
OleDbDataReader rdr = cmd.ExecuteReader();
if(rdr.Read())
// record exists
else
//Not exists
You should do two things:
If you are just checking the presence of a tag called Programming, you should change your query to return a COUNT instead of returning all rows.
SELECT TOP 1 Column1 FROM Table1 WHERE Tags = 'Programming'
You should check the returned set in the reader to see if there are any rows. If there are, then it means that the tag exists.

Categories