I am using a SQLite database. Since drop/rename/reorder columns are not supported in SQLite (using alter table commands), I am writing customized methods for the following tasks: (taking backup of existing table, then creating a new table with matching requirements and so on..) which is described in several other threads.
The following are the DB operations:
DROP columns
RENAME (columns and datatype)
ADD columns
REORDER columns.
I am wondering in what order should these operations be done? My confusion is mainly around whether drop should come before rename columns or the other way?
Also I need some pointers on how to rename columns including datatype and moving data around?
Any thoughts?
First, create a backup of your database in case something goes wrong during the following instructions.
The order of operations should be CREATE newtable, INSERT INTO newtable, DROP oldtable.
Create a new table with the correct column names and datatypes for each column. Then just do something like this:
INSERT INTO new_table(columns, ...)
(SELECT columns, ...
FROM old_table)
You may need to perform casts on different datatypes if the new datatype isn't directly compatible with the old datatype.
You will need to make sure that the columns you select from your old table are in the same order as defined by the columns in your new table in your INSERT INTO statement.
After data is inserted into your new table, you can then verify that all data has been inserted correctly. Be sure to update any foreign key references in your other tables to avoid any issues with foreign key constraints.
Then you can drop the old table and rename the new table to the name of your old table:
DROP old_table;
ALTER TABLE new_table_name RENAME TO old_table_name;
Related
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
The issue is like , I got two tables X & Y. When records are added to table X , columns should be added to the table Y in parallel.
http://prntscr.com/3owqfe <-- Provides a clear Idea.
I tried it with triggers , but seems like the triggers doesnt allow CREATE TABLE or ALTER TABLE. Anyway as I'm using Linq , Im trying to achieve that via Linq. Any suggestions ?
Edited: For the record the below trigger worked , but with an exception.
create trigger AddItemToCommon ON [SEP].[dbo].[ItemMaster]
FOR INSERT
AS BEGIN
declare #PAYID varchar(max)
select #PAYID = payCode from INSERTED
ALTER TABLE [SEP].[dbo].[CommonPayrollItems]
ADD sampleCol varchar(max)
END
Anyway it will only run once because , there cannot be more than 1 column of the same name. But if I can retrieve the row values grom ItemMaster table , it's still possible with triggers. Which I tried to replace sampleCol with #PAYID which results in Syntax error.
Linq does not have functionality to create or alter tables. You could however use the underlying connection of your Linq Datacontext to execute any SQL statement:
DataContext.ExecuteCommand(...)
And use that to run your alter table statement. This will not update your Linq model of that table though.
If you plan to do this at runtime, you might want to reconsider your data model and create a third table (eg. STable2Extended) that contains a foreign key to both STable and STable2 combined with the applicable value for that column.
You could then add the STable2Extended to the datamodel and query it easily when you need the extended properties on STable2 without dynamically modifying tables.
I want to generate EDM from my database file (.mdf), but i don't want to work with all columns. How can i skip these columns from .edmx?
You can't select specific columns at the time of generation. But, if you only want to work with a subset of columns, let the EDM generate the entire table; then in the designer surface you can select the columns you don't need and hit delete to remove them from the model.
One note is that if your database has certain constraints, such as non-nullable columns with no default value, an exception will be thrown if you try to add or update entities without those columns in your model.
You have to do this manually.
Obviously you can map tables as show here, but then you have to go through and manually remove columns. At least this is what I have been told.
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.
Is there a simple solution for duplicating table rows in SQL Server as well as all table rows with foreign keys pointing to the cloned table row? I've got a "master" table and a bunch of "child" tables which have a foreign key into the ID of the master table. I need to not only create a perfect copy of the master table, but clone each and every child table referencing the master table. Is there a simpler way to do this than creating a new row in the master table, copying in the information from the row to be cloned, then going through each child table and doing the same with each row pointing to the cloned row in the master table?
I'm using a SQL Server 2005 Database accessed through C# ASP.net MVC 1.0.
If by "simple" you mean is there is a procedure that can be called to do it, no there is not. However, you can use the INFORMATION_SCHEMA views such as INFORMATION_SCHEMA.COLUMNS and INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS to query for the columns in a table or the list of related tables and dynamically build your INSERT statements to copy one row to another. Of course, this does not account for other uniqueness constraints that might be on the tables (e.g. a table with a Name column which requires that the values be unique).