Selecting column names and data types of columns as a table - sql

I want to select column names of Table1 as rows of column1 of Table2 and data types of Table1 columns as rows of column2 of Table2.
So if Table1 is like this.
Name Age Graduation Date
John 21 11.11.2015
Hillary 23 7.09.2015
I want to get this table by query.
Name String
Age Long
Graduation Date Date
What should be my SQL query?
(I'm gonna use this in an Windows form application which uses OLEDB connection to get data from an mdb file.)

I'm gonna use this in an Windows form application which uses OLEDB
connection to get data from an mdb file
You can get the informations you need via con.GetOleDbSchemaTable:
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
connection.Open();
DataTable tableColumns = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, new object[] { null, null, "Table1", null }));
foreach (DataRow row in tableColumns.Rows)
{
var columnNameColumn = row["COLUMN_NAME"];
var dateTypeColumn = row["DATA_TYPE"];
var ordinalPositionColumn = row["ORDINAL_POSITION"];
...
}
}
You will find column-names and types in this DataTable. Ref.

Related

How can get correct Column Name from Database with Npgsql?

This is my table in database:
CREATE TABLE public.test
(
id integer NOT NULL DEFAULT nextval('test_id_seq'::regclass),
hc character varying(30),
"Hc" character varying(30),
"HC" character varying(30),
f character varying(30),
"F" character varying(30),
f1 character varying(30),
te numeric(2,2),
CONSTRAINT test_pkey PRIMARY KEY (id)
)
If i get a Table Definition by Npgsql from vb.net:
select * from test where null = null
Result: some colums had changed name:
Ex: Hc => Hc1,HC => HC2
How can get correct Column Name from Database with Npgsql?
It seems that you (directly or indirectly) use DbDataAdapter.Fill which renames columns as follows if necessary:
If the DbDataAdapter encounters duplicate columns while populating a
DataTable, it generates names for the subsequent columns, using the
pattern "columnname1", "columnname2", "columnname3", and so on.
Apparently, this deduplication process treats column names in a case-insensitive way which is why the columns also get renamed in your example. There is no way to turn off this behavior directly (see AdapterUtil.cs,2402).
A work around would be to use an additional SqlCommand and use SqlDataReader.GetName to obtain the exact column names and then change the columns of the DataTable accordingly. This could be done as follows:
Dim query = "select * from test where null = null"
' setup connection
Dim connection As New NpgsqlConnection(
String.Format("Server={0};Port={1};Database={2};User Id={3};Password={4};",
host, port, database, user, password))
connection.Open()
' fill data table from query
Dim table As New DataTable
Using adapter = New NpgsqlDataAdapter(query, connection)
adapter.Fill(table)
End Using
' correct column names
Using command = New NpgsqlCommand(query, connection)
Using reader = command.ExecuteReader()
For i = 0 To table.Columns.Count - 1
table.Columns(i).ColumnName = reader.GetName(i)
Next
End Using
End Using
' display table in DataGridView
view.DataSource = table

SSIS update a column with a result of an sql select

I was wondering if there's a way of updating a column inside a dataflow task by running a select on every row?
Here's the situation :
Let's take this as our start position. I collect info from 2 files, then I merge them, and I add a column with the derived column tool. Is there a way of populating this column by performing a select on every row using the values of the the row?
Ex :
SELECT Count(*) AS cnt
FROM TABLE T
WHERE T.COLUMN1 = ROW.COLUMN3
AND T.COLUMN2 = ROW.COLUMN5
I don't know if I'm just not phrasing my need properly but I couldn't get any results
Thank you
You should be able to do this with a Lookup Transformation.
EDIT based on comment:
If you don't want to use a lookup due to the size of the table, you can do exactly what you want with a Script Component. You can create and execute your SQL Command for each row of the dataflow just like you would in any .net application.
I was able to do it with a Script Component
1- I've removed the Derived Column
2- I've created a string variable where I stored the query whith a wildcard string to replace every value that I need to get from the row.
3- I've passed this variable allong with one containing the connecection string info to the Script Component
4- I've added a new column to the Output Columns of the Script Component
5- Added using System.Data.OleDb;
6- Created 2 variables :
string jourFerieQuery;
string dbcsoledbschema;
7- Updated the PostExecute() to put the values of my SSIS variables into the script variables :
public override void PostExecute()
{
base.PostExecute();
jourFerieQuery = Variables.jourFerieQuery;
dbcsoledbschema = Variables.dbcsoledbschema;
}
8- Added a method :
int GetData(string cs, string query)
{
OleDbConnection conn = new OleDbConnection(cs);
conn.Open();
OleDbCommand cmd = new OleDbCommand(query, conn);
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
conn.Close();
return (int)dt.Rows[0][0];
}
9- Updated the Input0_ProcessInputRow(Input0Buffer Row) :
public override void Input0_ProcessInputRow(Input0Buffer Row)
{
string query = jourFerieQuery.Replace("[1]", Row.CODDEVI).Replace("[2]", Row.DATCRBEZEROCONGE.ToString());
Row.Keep = GetData(dbcsoledbschema, query);
}
My query returns a count that's why the method I've added returns an int
You can do that through a script component (transformation).
Add an output of Ct.
I use System.Data.OleDB as it matches the SSIS package connection string.

Retrieve ID from database in mvc

I am trying to retrieve a specific id from a table so that I can get the correct record in my database and use that information. Is there anyway where I can get the actually numerical value of the id from the table. I have tried using linq to SQL but it just queries the database and returns the string like this:
Dim id = From data In dbServer.UserTables Where data.Username = user.username And data.userPassword = user.userPassword Select data.UserID
It does work because then if I count id if it is greater than 1 it will work. But trying to send the value on for example in session state will only have "From data In dbServer.UserTables Where data.UserID = user.username And data.userPassword = user.userPassword Select data.UserID" instead of the actual number. How can I do this correctly?
A Linq query will return a set of data, even if there is only one result.
This will get you an integer (possibly a nullable integer, I can't test right now), that you will have to check for value different than 0 (or null, if it's a nullable).
Dim id = (From data In dbServer.UserTables Where data.UserID = user.username And data.userPassword = user.userPassword Select data.UserID).FirstOrDefault()

Value copy function batch processing

I'm trying to copy values from one ID to another ID.
The ID and the timestamp are primary keys.
String sqlString = "SELECT * FROM Values WHERE ID = #ID";
var sqlCommand = new SqlCommand(sqlString, sqlConnect);
sqlCommand.Parameters.Add("#ID", SqlDbType.UniqueIdentifier).Value = ID;
using (var reader = sqlCommand.ExecuteReader())
{
while (reader.Read())
{
time = reader["Time"];
dt = DateTime.Parse(time.ToString(), CultureInfo.InvariantCulture);
value = reader["Value"];
insertData(IdDestination, dt, value);
}
}
This function is working, but if I have 10.000 table rows, then it's very slow.
I was thinking about using SqlBulkCopy, but this doesn't work for me because I need to change the Destination ID. Another problem is that sometimes, the values I want to copy already exist, so I need a rollback or commit. Update is also not working because of losing important data.
Does anyone have an idea about what kind of batch processing would work for me?
I'd like to insert 1000 rows or more at the same time without having to call my insert function a thousand times.

How to make this table query more efficient

I've added a dataset , and a table adapter to my C# project.(The dataset and tableadapter was added via DataSources box)
In this query , I get table data , then filter , then I will iterate and fill a listbox.
listBox1.Items.Clear();
ETPDataset.t_USR_UsersDataTable tbl = (new ETPDataset.t_USR_UsersDataTable());
ETPDatasetTableAdapters.t_USR_UsersTableAdapter tblAdap = new TestIntellisenseSql.ETPDatasetTableAdapters.t_USR_UsersTableAdapter();
tblAdap.Connection.ConnectionString = scon.ConnectionString;
tblAdap.Fill(tbl);
ETPDataset.t_USR_UsersRow[] rows2;
rows2 = (ETPDataset.t_USR_UsersRow[])tbl.Select("USR_RECORDID > 60");
foreach (ETPDataset.t_USR_UsersRow drow in rows2)
{
listBox1.Items.Add(drow.USR_UserID);
}
This is my problem
tblAdap.Fill(tbl);
because this line of code will fetch ALL data(problem for big tables) , how can i fix it ?
-Thanks
Create a new method on your adapter to use a where clause to filter the data at the database.