Copy a table and dependencies - sql-server

I made an error in updating a table and the quickest solution was to replace the table with a backup from previous night. No other changes had been made to the table prior to the backup.
I renamed the existing table that had errors to table_old and used SQL import tool to import the backup copy of table into the correct database. I realize that my dependencies are not present for the copied table.
Q: is is possible to copy the dependencies into the table that I used for the backup? I assume the dependencies would be included if I imported data + Schema?
Regards,

I would try this:
Rename the new table to table_backup. Rename original table to its original name table. Truncate table table. Insert table Select * from table_backup. You may need to set identity insert on if you have such a column in the table.

Related

Cloning a table without importing row data

I need to make a provisionary table (TAB_PROV). This table will have its origin in a main table (TAB_MAIN). I need everything from the main table, except the data (rows).
I searched for some examples and none of them worked for me
CREATE TABLE TAB_PROV LIKE TAB_MAIN
CREATE TABLE TAB_PROV AS TAB_MAIN
You can just simply do:
SELECT *
FROM TAB_MAIN
INTO TAB_PROV
WHERE 1 = 2
Since the WHERE condition will never be true, no data is ever copied - but the table structure is replicated - TAB_PROV is created and has the same column as TAB_MAIN. This does NOT however copy any constraints (check or default constraints) or triggers over - it only recreates the columns (and their datatypes).
If you want a real and complete "copy" of your table, then you should use the "Script Table" function in SSMS to get the SQL needed for TAB_MAIN and then adapt it to create TAB_PROV from it.
In SQL Server Management Studio, you can right-click the table and select
Script Table as -> Create To -> New Query Editor Window
This will create just the table creation script for you.
You can also try the code below but it will copy everything.
SELECT *
INTO NewTable
FROM OldTable
TRUNCATE TABLE NewTable

Cannot delete column with only null values when BlockOnPossibleDataLoss=true

I'm using a blue-green deployment strategy with expand contract database pattern. To achieve that on my database deploy schema I've setted the property BlockOnPossibleDataLoss=true because on Expand phase I can modify my database without any break change with the old version.
I had a column that is not necessary anymore so I followed those steps:
I've changed this column to allow null values
Then my new records don't fill this column anymore
I ran a script that setted null for this column to all table records
Now I need to delete this column, but even with all records with NULL value for this column I can't because I got this error:
Rows were detected. The schema update is terminating because data loss
might occur.'
How can I delete this column even using BlockOnPossibleDataLoss=true?
Create the table with the new schema (without the column you wan't to drop) with a temporary name. Something like tmp_YourTable (Not a temporary table)
Insert all data from the source table, to the newly created table
Drop the source table
Rename the new table, to the old table name. EXEC sp_rename 'tmp_YourTable', 'YourTable';

update data when importing a duplicate record in SQL

I have a unique requirement - I have a data list which is in excel format and I import this data into SQL 2008 R2., once every year, using SQL's import functionality. In the table "Patient_Info", i have a primary key set on the column "MemberID" and when i import the data without any duplicates, all is well.
But some times, when i get this data, some of the patient's info gets repeated with updated address / telephone , etc., with the same MemberID and since I set this as primary key, this record gets left out without importing into the database and thus, i dont have an updated record for that patient.
EDIT
I am not sure how to achieve this, to update some of the rows which might have existing memberIDs and any pointer to this is greatly appreciated.
examples below:
List 1:
List 2:
This is not a terribly unique requirement.
One acceptable pattern you can use to resolve this problem would be to import your data into "staging" table. The staging table would have the same structure as the target table to which you're importing, but it would be a heap - it would not have a primary key.
Once the data is imported, you would then use queries to consolidate newer data records with older data records by MemberID.
Once you've consolidated all same MemberID records, there will be no duplicate MemberID values, and you can then insert all the staging table records into the target table.
EDIT
As #Panagiotis Kanavos suggests, you can use a SQL MERGE statement to both insert new records and update existing records from your staging table to the target table.
Assume that the Staging table is named Patient_Info_Stage, the target table is named Patient_Info, and that these tables have similar schemas. Also assume that field MemberId is the primary key of table Patient_Info.
The following MERGE statement will merge the staging table data into the target table:
BEGIN TRAN;
MERGE Patient_Info WITH (SERIALIZABLE) AS Target
USING Patient_Info_Stage AS Source
ON Target.MemberId = Source.MemberId
WHEN MATCHED THEN UPDATE
SET Target.FirstName = Source.FirstName
,Target.LastName = Source.LastName
,Target.Address = Source.Address
,Target.PhoneNumber = Source.PhoneNumber
WHEN NOT MATCHED THEN INSERT (
MemberID
,FirstName
,LastName
,Address
,PhoneNumber
) Values (
Source.MemberId
,Source.FirstName
,Source.LastName
,Source.Address
,Source.PhoneNumber
);
COMMIT TRAN;
*NOTE: The T-SQL MERGE operation is not atomic, and it is possible to get into a race condition with it. To insure it will work properly, do these things:
Ensure that your SQL Server is up-to-date with service packs and patches (current rev of SQL Server 2008 R2 is SP3, version 10.50.6000.34).
Wrap your MERGE in a transaction (BEGIN TRAN;, COMMIT TRAN;)
Use SERIALIZABLE hint to help prevent a potential race condition with the T-SQL MERGE statement.

How to import to a SQL Server table and start primary key where left off

I can't seem to find an answer to this. I am very new to SQL Server. I have been trying to set up a database to be updated daily for a website.
There is a .CSV file produced daily. I have set up a script to copy the file, edit the text and import the file into a table in SQL Server 2012.
There are 16 fields in the .CSV file. I have a 17th field in the table I import it into.
The 17th field is the Primary Key which I have set to autoincrement.
My problem is this:
I'm implementing this as a new process. This is already set up and in operation on an older server. The older server was using MySql. The Primary Key was left off at 81,720,024.
I have set the Primary Key field to autoincrement with a seed of 81720024.
Every time I update the table I truncate the table first and the import from a staging table. The Primary Key always starts at 81720024. I need to have it increment from the last entry it had. Please help!
Try deleting from the table instead of truncating.

What is the equivalent of 'CREATE TABLE ... LIKE ..." in SQL Server

I am working with SQL Server (I am a SQL Server noob) and trying to alter a table. I want to CREATE TABLE LIKE to safely store data while I drop keys and constraints and all the other rigamorole that SQL Server seems to require when altering on the original table but I have not been able to find a match to that command...
you want to recreate the same structure?
how about this
SELECT *
into test
FROM myRealTable
where 0=1
no data will be inserted into the new table
You can do
SELECT * INTO #MyTable_tmp FROM MyTable
Then modify your MyTable, and copy your data back in. Other approaches I've seen is to create a new table call it Mytable_Tmp (Not a temp table), which will be your new table.
Then copy your data doing any migrations you need. Then you will drop the original table and do a rename on Mytable.
Or you can get one of the many excellant tools that compare databases and generate difference scripts or VSTS DB Edition (Comes with developer) and you can do a diff script from a project file to a DB.
Edit
When you run SELECT * INTO #MyTable FROM MyTable, SQL Server creates a new temporary table called #MyTable that matches each column and data type from your select clause. In this case we are selecting * so it will match MyTable. This only creates the columns it doesn't copy defaults, constraints indexes or anything else.

Resources