How to copy table from Production to Development? - sql

I am working on Development Server Named as SQLDEV01 and the db name is University and the table name is cse.students. During my work on table cse.students I lost some rows so I need to get the all the exact data from Production server.production Server Name is SQLPROD01.
How can I query to get the production data without using SSIS?

Setup a linked server from the development to production servers before doing the following from SSMS. All code should be executed on the development server.
http://technet.microsoft.com/en-us/library/ms188279.aspx
-- On Development server [SQLDEV01]
TRUNCATE TABLE [University].[cse].[students];
GO
-- Use link server to move data
INSERT INTO
[University].[cse].[students]
SELECT
*
FROM
[SQLPROD01].[University].[cse].[students]
GO
This assumes there are no identity columns on the target.
If you do have identity columns, turn on/off allow inserts before/after executing the above insert.
-- Before Insert, execute this statement
SET IDENTITY_INSERT [University].[cse].[students] ON
GO
-- After Insert, execute this statement
SET IDENTITY_INSERT [University].[cse].[students] OFF
GO
You can also create an ad-hoc connection using the OPENROWSET command.
http://technet.microsoft.com/en-us/library/ms190312.aspx
INSERT INTO
[University].[cse].[students]
SELECT
PRD.*
FROM
OPENROWSET('SQLNCLI', 'Server=SQLPROD01;Trusted_Connection=yes;',
'SELECT * FROM [University].[cse].[students]') AS PRD;
I did not check the syntax for your environment, please check.
If add hoc queries are set off (0), have the DBA turn them on (1) temporarily. Execute the following on the production server.
http://msdn.microsoft.com/en-us/library/ms187569.aspx
-- Show all settings
sp_configure 'show advanced options', 1;
RECONFIGURE;
GO
-- What is the current setting?
sp_configure
GO
-- Allow add hoc queries
sp_configure 'Ad Hoc Distributed Queries', 1;
RECONFIGURE;
GO
If (s)he does not allow that, you are stuck with a physical linked server.
If you are using delegation - choice #3, you have to watch out for the double hop issue.
http://blogs.msdn.com/b/sql_protocols/archive/2006/08/10/694657.aspx
I would configure the linked server with a specific account on production that has rights to select the data. See choice #4.

There are a few ways to do this. One that is pretty much failsafe is the following:
In Microsoft SQL Management Studio expand the server node for the source server - Then expand the Databases node. Right click on the source database and select Tasks -> Generate Scripts. When the dialog pops up click next. Select the "Select specific database objects" radio button. Expand the Tables node as check the table you want to copy. Click the next button at the bottom. Click the advanced button. In the options that pop up for Script DROP and CREATE select Script DROP and CREATE on the right. For the option Type of data to script select schema and data on the right. Click OK. Now back on the main dialog you need to select "Save to Clipboard" or "Save to new query window". I usually select clipboard because I am usually going to a different server but select what works best for you. Click next. Click next again and the script will generate according to your selections. Now just run that script on the destination database.

please use this query generalized query by replacing your entries
select * into targetTable from [sourceserver].[sourcedatabase].[dbo].[sourceTable]

Related

Change the database connection programmatically

In Oracle SQL Developer, I need to switch the active database connection manually. Is there a command that will connect to a different database programmatically, assuming that the login credentials are already saved? I'm trying to avoid clicking on the drop-down menu at the top right of the window which selects the active connection.
Perhaps I should rather have a single SQL file per database? I could understand that argument. But this to prepare to migrate some tables from one database to another and so it's nice to have all of the context in one file.
On database1, run a query on table1 which is located in schema1.
-- manually switch to database1 (looking for a command to replace this step)
ALTER SESSION SET CURRENT_SCHEMA = schema1
SELECT * FROM table1;
On database2, run a query on table2 which is located in schema2.
-- manually switch to database2
ALTER SESSION SET CURRENT_SCHEMA = schema2
SELECT * FROM table2;
Looks like this is well documented here
Use this command
CONN[ECT] [{<logon>| / |proxy} [AS {SYSOPER | SYSDBA | SYSASM}] [edition=value]]
You need a DDL TRIGGER to perform an event after your presql
CREATE TRIGGER sample
ON TABLE
AFTER
Event
........
THEN
ALTER SESSION SET
CURRENT_SCHEMA = schema2
SELECT * FROM table2;
I don't know of a way in which to change your selected connection in SQL Developer, but there is a programmatic method for temporarily changing the connection under which the script commands are run, as #T.S. pointed out. I want to give a few examples, which might be helpful to people (as they would have been for me).
So let's say your script has part A and part B and you want to execute them one after the other but from different connections. Then you can use this:
CONNECT username1/password1#connect_identifier1;
-- Put commands A here to be executed under this connection.
DISCONNECT; -- username1
CONNECT username2/password2#connect_identifier2;
-- Put commands B here to be executed under this connection.
DISCONNECT; -- username2
The connect_identifier part identifies the database where you want to connect. For instance, if you want to connect to a pluggable database on the local machine, you may use something like this:
CONNECT username/password#localhost/pluggable_database_name;
or if you want to connect to a remote database:
CONNECT username/password#IP:port/database_name;
You can omit the password, but then you will have to input it in a prompt each time you run that section. If you want to consult the CONNECT command in more detail, this reference document may be useful.
In order to execute the commands, you would then select the code that you are interested in (including the relevant CONNECT commands) and use Run Script (F5) or just use Run Script (F5) without selecting anything which will execute the entire script file. SQL Developer will execute your commands, put the output into the Script Output tab and then stop the connection. Note that the output of SELECT commands might be unpleasant to read inside Script Output. This can be mitigated by running the following command first (just once):
SET sqlformat ansiconsole;
There is also Run Statement (Ctrl+Enter), but do note that Run Statement (Ctrl+Enter) does not seem to work well with this workflow. It will execute and display each SELECT statement into a separate Query Result tab, which is easier to read, BUT the SELECT query will always be executed from the context of the active connection in SQL Developer (the one in the top right), not the current code connection of the CONNECT statement. On the other hand, INSERT commands, for instance, DO seem to be executed in the context of the current code connection of the CONNECT statement. This (rather inconsistent) behaviour is probably not what you want, so I recommend using Run Script (F5) as described above.

How to drop a database when it's currently in use?

NB. I don't want to mark the check box in the wizard for deletion. This question's strictly about scripting the behavior.
When I run the following script to get a fresh start, I get the error that the database Duck can't be deleted because it's currently in use.
use Master
drop database Duck
drop login WorkerLogin
drop login AdminLogin
go
Be that as it may (even though I'm the only user currently in the system and I run no other queries but that's another story), I need to close all the existing connections. One way is to wait it out or restart the manager. However I'd like to script in that behavior so I can tell the stubborn server to drop the duck down. (Yes, "typo" intended.)
What do I need to add to the dropping statement?
Try below code.
USE master;
ALTER DATABASE [Duck] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
DROP DATABASE [Duck] ;
For deep discussion see this answer.
You have to kill first all active connections before you can drop the database.
ALTER DATABASE YourDatabase SET SINGLE_USER WITH ROLLBACK IMMEDIATE
--do you stuff here
ALTER DATABASE YourDatabase SET MULTI_USER
http://wiki.lessthandot.com/index.php/Kill_All_Active_Connections_To_A_Database
How do you kill all current connections to a SQL Server 2005 database?
if you're ssms tab is not currently on the db to be dropped (meaning you are in the master db), then these will help:
https://dba.stackexchange.com/questions/2387/sql-server-cannot-drop-database-dbname-because-it-is-currently-in-use-but-n
https://dba.stackexchange.com/questions/34264/how-to-force-drop-database-in-sql-server-2008

Modify table creation date

Is it possible to modify the table creation date of a table? The date which we see on right clicking a table > properties > Created date or in sys.tables.create_date.
Even though the tables were created months ago, I want it to look like they were created today.
No more than you can change your birthday, and why would you want to ?
You could just
select * into #tmp from [tablename]
drop table [tablename]
select * into [tablename] from #tmp
That would rebuild the table and preserve the structure (to a point). You could script a new table , copy data then drop and rename. As above.
In SQL Server 2000, you could do this by hacking into the system tables with the sp_configure option 'allow updates' set to 1.
This is not possible in SQL Server 2005 and up. From Books Online:
This option is still present in the sp_configure stored procedure,
although its functionality is unavailable in Microsoft SQL Server 2005
(the setting has no effect). In SQL Server 2005, direct updates to the
system tables are not supported.
In 2005 I believe you could "game the system" by using a dedicated administrator connection, but I think that was fixed shortly after RTM (or it needs a trace flag or some other undocumented setting to work). Even using DAC and with the sp_configure option set to 1, trying this on both SQL Server 2005 SP4 and SQL Server 2008 R2 SP1 yields:
Msg 259, Level 16, State 1
Ad hoc updates to system catalogs are not allowed.
Who are you trying to fool, and why?
EDIT
Now that we have more information on the why, you could create a virtual machine that is not attached to any domain, set the clock back to whatever date you want, create a database, create your objects, back up the database, copy it to the host, and restore it. The create_date for those objects should still reflect the earlier date, though the database itself might not (I haven't tested this).
You can do this by shifting the clock back on your own system, but I don't know if I'd want to mess with my clock this way after SQL Server has been installed and has been creating objects in what will become "the future" for a short period of time. VM definitely seems safer to me.

Insert Data From One Server To Another?

If I want to run this sort of query in SQL Server, how can I do the same query from one server I am connected to to another?
I tried adding "[ServerName1]." before "[DatabaseName1].[dbo]..." and "[ServerName2]." before "[DatabaseName2].[dbo]..." but that didn't seem to work.
INSERT INTO [DatabaseName1].[dbo].[TableName]
([FieldName])
SELECT [FieldName] FROM [DatabaseName2].[dbo].[TableName]
Is this possible?
Yes you would use the server-name before the whole rest of object-name like:
myserver.mydatabase.dbo.mytable
However you first have to set up linked servers. Look up linked servers in BOL.
If you have adhoc distributed queries enabled you can use OPENDATASOURCE. Setting up a linked server is another option. Not sure of the pros and cons of each approach.
INSERT INTO [DatabaseName1].[dbo].[TableName]
SELECT FieldName
FROM OPENDATASOURCE('SQLNCLI',
'Data Source=Server\InstanceName;Integrated Security=SSPI')
.DatabaseName2.dbo.TableName
The best way to do this would be to create a "linked server" between the two. You will need appropriate permissions to do this.
Then it's just a matter of accessing the databases using your linkedserver name.
Ex: [linkedserver].databasename.dbo.tablename
To create a linkedserver, go to server objects->right click on linked servers->click on 'new linked server'.
In SSMS, Go to Query -> 'SQLCMD Mode'
DECLARE #VERSION VARCHAR(1000)
:CONNECT Soruce_Server_Name
SELECT ##VERSION AS [SQL_VERSION]
INTO
:CONNECT Destination_Server_Name
[MSSQLTips].[dbo].[TEST]
Now on the Destination Server, execute your select command to check your output. For E.g.
SELECT * FROM [CloverInfotech_DB].[dbo].[TEST]

select from access database file and insert to sql Database

I have an access database file (test.mdb) and I need to write a stored procedure which will select some records from tblTest in test.mdb and insert them into tbsqlTest in my sql database .
==> I need a SP like this :
BEGIN
select * into tblTest from [test.mdb].[tblTest]
where (my condition)
END
If you're willing to permit Ad Hoc Distributed Queries on your SQL Server, you could use OPENDATASOURCE to retrieve data from an MDB file.
SELECT * INTO dbo.TestAccess FROM OPENDATASOURCE(
'Microsoft.Jet.OLEDB.4.0',
'Data Source="\\server\share\somefolder\scratchpad.mdb"')...MyTable;
Or after creating the destination table, you might prefer:
INSERT INTO dbo.TestAccess
SELECT * FROM OPENDATASOURCE(
'Microsoft.Jet.OLEDB.4.0',
'Data Source="\\server\share\somefolder\scratchpad.mdb"')...MyTable;
In order to get those to run, I had to enable Ad Hoc Distributed Queries like this:
sp_configure 'show advanced options', 1;
RECONFIGURE WITH OVERRIDE;
GO
sp_configure 'Ad Hoc Distributed Queries', 1;
RECONFIGURE WITH OVERRIDE;
GO
I found configuration instructions on TechNet, but it didn't work for me until I added WITH OVERRIDE.
Edit: I added a sql-server tag to your question because I want to find out whether my suggestion is foolishly risky. Perhaps setting up the MDB as a linked server is a safer way to go here. I don't know.
If you are going to be doing this regularly;
Create an append query in design view that does what you want it to do, including the criteria by which to filter the query results.
View the query in SQL view.
Copy the SQL Text
Create a button on your form. Go to the properties window, under the event tab, and select the "on click" event. Click the ellipsis "..." and open the code.
Use this code:
Dim MyAppendString as String
MyAppendString = " (Code line 1) " & _
" (Code line 2) " & _
" (Last line) ";
docmd.runsql MyAppendString
Every time you click the button, it will execute the append query, hardcoded with the criteria you selected.
Let me know if you stick on any of these points. I'll send you more detailed instructions.