How to build Query dynamically using asp.net3.5 and c#.net - c#

i need create query dynamically in my .cs page. Actually what happens in my application is user can pass the column name and Table names from the page. by using those parameters(columns and tables) we need build Select query . we need retrieve those values from database and show in text format to user.there may multiple table and single table have multiple columns also.
please try yo help how to do this ny using asp.net3.5 and c3.net

So you need to have a dynamic query that populates its columns as per users requirement. It is not achievable but I have a nearby solution of it.
You can specify from which tables you want data and then using system functions create dynamic query of yours and get it done.

If nothing else, just create the query string dynamically and then pass it to the ADO.NET routines.
string qry = String.Format("SELECT {0} FROM Table", colName);

Related

SQL Server pre-deploy script to recreate table new columns and preserve data

I created a project in ASP.NET MVC with a separate database project which I run every time there is a table change. My only problem is that if I add one column for example, it will drop the entire database and recreate it and delete all data in the table.
Does anyone know of a pre-deployment script or a method I can use to add / remove / rename tables or column and at the same time preserve the integrity of my data? i.e keep my data while modifying my database
You can rename columns using SQL Server functions, but doing this risks breaking scripts used by other functions or stored procedures in your database. I don't endorse this practice, so I'm not posting about it below. Adding or removing columns is fair game.
You can add columns to a table by using the following query:
ALTER TABLE [YourTable]
ADD [ColumnName] [Datatype];
And you can drop columns using this query:
ALTER TABLE [YourTable]
DROP COLUMN [ColumnName];
These SQL commands will preserve the other columns in your table. If you want to change a column name I encourage you to set up a View in your SQL Server client and give the column an alias.
This can be accomplished using:
CREATE VIEW [ViewName]
AS
SELECT [ColumnName] AS [ColumnAlias]
FROM [TableName]
GO
You'd be able to perform SELECTS on the view in just the same way you can query SELECT on a normal table, except you can query the [ColumnAlias] instead of the [ColumnName]. You cannot perform INSERT or DELETE queries on a view, however

Save XML data into database as columns in C#

I'm writing an C# application that watch for newly created xml files, and I want to insert some of the data in these XML files to a SQL database. One file is one row in the database.
What is the best and easiest way to do this?
What I have done so far is to defined a DataTable with the columns I want from the XML. After that I use ReadXML on the DataSet. This give me a DataSet with one table and one row, and the columns I want. So far it's perfect. But I can't find a good way to ONLY insert this new DataRow into my MSSQL database. I don't have any unique ID for that row yet. Would this make it easier? I don't want to map my dataset with the database, I'm only doing an insert...
You can do something like this to get the ID:
string query = "INSERT INTO Employees (EmployeeID, Name, Phone) "+
"OUTPUT INSERTED.EmployeeID "+
"VALUES (NEWID(), 'John Kris', '99-99999')";
Guid lastId = (Guid)command.ExecuteScalar();
The rest of the things you do sound ok for me.
I used LINQ to SQL to solve this. I set it up somewhat like described here:
LINQ to SQL.
On the data context I used InsertOnSubmit.

How to insert to table with one-to-one relationship via dataset

I use asp.net 4 and DataSets for accessing the database. There are two tables with one-to-one relationship in the database. It means that both tables have the same column as a primary key (say Id), and one of tables has #identity on this column set.
So in general if we want to insert, we insert first into the first table, than insert into the second table with id.table2 = id of the corresponding record in table1.
I can imagine how to achieve this using stored procedure (we would insert into the first table and have id as an out parameter and then insert into the second table using this id, btw all inside one transaction).
But is there a way to do it without using a stored procedure? May be DataSets \ DataAdapters have such functionality built in?
Would appreciate any help.
Today it is so quiet here... Ok if anybody is also looking for such a solution, I've found a way to do it.
So our main problem is to get the id of the newly created record in the first table. If we're able to do that, after that we simply supply it to the next method which creates a corresponding record in the second table.
I used a DataSet Designer in order to enjoy the code autogeneration feature of the VS. Let's call the first table TripSets. In DataSet Designer right click on the TripSetsTableAdapter, then Properties. Expand InsertCommand properties group. Here we need to do two things.
First we add a new parameter into the collection of parameters using the Parameters Collection Editor. Set ParameterName = #TripId, DbType = Int32 (or whatever you need), Direction = Output.
Second we modify the CommandText (using Query Builder for convenience). Add to the end of the command another one after a semicolon like that:
(...);
SELECT #TripId = SCOPE_IDENTITY()
So you will get something like this statement:
INSERT INTO TripSets
(Date, UserId)
VALUES
(#Date,#UserId);
SELECT #TripId = SCOPE_IDENTITY()
Perhaps you will get a parser error warning, but you can just ignore it. Having this configured now we are able to use in our Business logic code as follows:
int tripId;
int result = tripSetsTableAdapter.Insert(tripDate, userId, out tripId);
// Here comes the insert method into the second table
tripSetTripSearchTableAdapter.Insert(tripId, amountPersons);
Probably you will want to synchronize this operations somehow (e.g. using TransactionScope) but it is completely up to you.

Fetching data from different table in asp.net

I want to fetch data from separate tables in sqlserver and display them together in GridView, Is that possible? if so then please suggest.
Thank you.
Yes, you can do that. Sample SQL is :
SELECT * FROM firstTable UNION ALL SELECT * FROM secondTable
Then you can get the results to datatable and bind that datatable to gridview.
Yes, that is possible, if both the returned result schemas are the same.
You would have to either join them at SQL level (with UNION) or at code level (with Enumerable.Union()).
Bottom line, you can only assign a single datasource to a control.
I can think in two ways of do it, the first is that the SQL query join the data in the desired way and return it merged.
The other is making a query that returns a DataSet with the 2 tables and merge in c# creating a third datatable via code with the columns we want and populating later from the obtained data.
I will use the first option if is posible..

DataAdapter Select string from base table schema?

When I built my .xsd, I had to choose the columns for each table, and it made a schema for the tables, right? So how can I get that Select string to use as a base Select command for new instances of dataadapters, and then just append a Where and OrderBy clause to it as needed?
That would keep me from having to keep each DataAdapter's field list (for the same table) in synch with the schema of that table in the .xsd file.
Isn't it common to have several DataAdapters that work on a certain table schema, but with different params in the Where and OrderBy clauses? Surely one does not have to maintain (or even redundently build) the field list part of the Select strings for half a dozen DataAdapters that all work off of the same table schema.
I'm envisioning something like this pseudo code:
BaseSelectString = MyTypedDataSet.JobsTable.GetSelectStringFromSchema() // Is there such a method or technique?
WhereClause = " Where SomeField = #Param1 and SomeOtherField = #Param2"
OrderByClause = " Order By Field1, Field2"
SelectString=BaseSelectString + WhereClause + OrderByClause
OleDbDataAdapter adapter = new OleDbDataAdapter(SelectString, MyConn)
Each table has a default query (The one on top with the check on it). When you dragged your tables in to the dataset to create the query, it wrote a SQL statement which it uses to schema your table. Keep that query simple, you might not actually use it in code, and you can always edit that query to update the table schema.
Every time you open the default query it connects to your datasource and allows you to select new columns that weren't in there before. If you want to update your existing columns, delete all the columns out of the table before you attempt to open the query. When you save the query, your updated columns get added back.
Make sure your connection string has permissions to view column information.
You can add multiple queries to a single TableAdapter. TableAdapters in the designer appear sectioned with a table schema at the top, and queries on the bottom. The default query will control which columns are available for output from the other queries. To add an additional query, right click on the TableAdapter and select "Add->Query" or if you are selecting the bottom part of the TableAdapter you can select "Add Query...". Any new SQL query you create will start off with the SQL from the default query. You give each new query a method name which you can use instead of the default query's "Fill" or "GetData" methods. The assumption is that each new query will have a result set that matches the default query even though they can have different "where" clause parameters.
In short
You may have a single TableAdapter for each table, just add multiple queries.
Each additional query can have different "Where" clause parameters as long as they all return the same columns.

Categories

Resources