copy results of a view query into azure sql - sql-server

I'm trying to create historic data for my company; previously i asked how to copy a table with a timestamp into the same mssql database. realistically, it dawned on me that what i really need to do is the following
1) log onto my local mssql box
2) run a query of a view (select * from view_whatever)
3) copy the results of the query and add a timestamp into another database, hosted using azure SQL
if i were doing this from the same database to another table, i'd something like this:
DECLARE #copyDate DATETIME2 = CURRENT_TIMESTAMP
INSERT INTO Hst_Opportunities
SELECT OppName, Oppvalue, #copyDate AS copyDate
FROM dbo.opportunities
the from part is what im struggling with - how do i copy cross server and database when the source database is MSSQL and the target is Azure SQL?

Based on my test, it appears you could create a linked server on your local box and insert the data using four part name:
EXEC master.dbo.sp_addlinkedserver #server = N'SQLAZURE', #srvproduct=N'sqlazure', #provider=N'SQLNCLI', #datasrc=N'NAME.database.windows.net', #catalog=N'TestDb'
EXEC master.dbo.sp_addlinkedsrvlogin #rmtsrvname=N'SQLAZURE',#useself=N'False',#locallogin=NULL,#rmtuser=N'USERNAME',#rmtpassword='Password'
GO
DECLARE #copyDate DATETIME = CURRENT_TIMESTAMP;
INSERT INTO [SQLAZURE].[TestDb].[Schema].[Table]
SELECT TOP (10)
[Column1]
,[Column2]
,#copyDate AS copyDate
FROM [Localdb].[Schema].[View];

Related

Insert from SQL to SQLBase with linked Server

how can i insert from SQL Server to a SQLBase Database using linked Server?
Here are various examples of the correct syntax for SQLServer to SQLBase assuming your LinkedServer is called 'ISLANDLINK' . Note the two dots.
or Go here for the full script and explanation : SQLServer to SQLBase via LinkedServer
or Go here for another example: SQLServer to SQLBase via LinkedServer (more)
--Select:
SELECT * FROM OPENQUERY( ISLANDLINK, 'Select * from SYSADM.BUDGET where DEPT_ID = ''MIS'' ')
--Update:
UPDATE [ISLANDLINK]..[SYSADM].[BUDGET]
SET [BGT_YEAR] = 2016
WHERE DEPT_ID = 'MIS'
GO
--Insert:
INSERT INTO [ISLANDLINK]..[SYSADM].[EMPLOYEE]
([EMPLOYEE_ID]
,[LAST_NAME]) VALUES (99 ,'PLUMAS' )
GO
--Delete:
DELETE FROM [ISLANDLINK]..[SYSADM].[EMPLOYEE]
WHERE [LAST_NAME] = 'PLUMAS'

SQL Server 2012 - Insert into linked server table using openquery

I have a linked server Remoteserver containing a table that holds file and folder names from a dir
When I am on the remote server I can run a built in procedure (xp_dirtree) and populate the 'files' table but what i need to do is to run a query from the local SQL server that does this:
Delete all records from the [Files] table on Remoteserver
Insert data that comes from the stored procedure:
INSERT [Remoteserver].[dbo].[files] (subdirectory,depth,isfile)
EXEC master.sys.xp_dirtree '\\Fileserver\DBBackup',1,1;
Select the 'subdirectory' column
I tried some things using openquery and i am able to select existing records but unable to do the insert.
Any help is appreciated.
Try this
INSERT INTO OPENQUERY([Remoteserver]
,'SELECT subdirectory, depth, [file] FROM [RemoteDB].[dbo].[files]')
EXEC master.sys.xp_dirtree '\\fileserver\DBBackup', 1, 1;
OR
INSERT INTO OPENQUERY([Remoteserver]
,'SELECT subdirectory,depth, [file] FROM [RemoteDB].[dbo].[files]')
select * from OPENQUERY([another_server_name], 'master.sys.xp_dirtree ''\\fileserver\DBBackup\temp'', 1, 1');
But in general you do not need to use OPENQUERY at all if Fileserver and Remoteserver are accessible from the local machine.
INSERT INTO [Remoteserver].[RemoteDB].[dbo].[files] (subdirectory, depth, isfile)
EXEC master.sys.xp_dirtree '\\Fileserver\DBBackup',1,1;

Is there a way to query SQL Server linked server without hardcoding database name?

I found samples where the code:
SELECT * FROM [legacyserver].[database].[schema].[table]
was expressed as:
SELECT * FROM [legacyserver]...[table]
but isn't working for me.
It gives me the error:
An invalid schema or catalog was specified for the provider "MSDASQL" for linked server "legacyserver".
I'm using for legacy server SQL SERVER 2000 and for the new server SQL SERVER 2012.
I tried creating the linked server using:
EXEC sp_addlinkedserver
#server = 'legacyserver',
#srvproduct = '',
#provider = 'MSDASQL',
#provstr = 'DRIVER={SQL Server};SERVER=legacyserver;DATABASE=database;Trusted_Connection=Yes;',
and:
EXEC sp_addlinkedserver
#server = 'legacyserver',
#srvproduct = '',
#provider = 'MSDASQL',
#provstr = 'DRIVER={SQL Server};SERVER=legacyserver;Trusted_Connection=Yes;',
#catalog = 'database';
Is it possible to create the script without hard coding the database name?
I need to create a really big migration script and it need to use a development, acceptance and production databases, and it will be to much work and error prone to change it using replace in the text editor.
UPDATE:
The legacy development, acceptance and production databases are exactly the same (except for the data) and each one have it's own server/instance and database name.
Due to segregation of duties, I can't develop something and deploy it, so I have no way to touch this script after acceptance. I will need to instruct someone else to do so, and if he/she will need to replace every occurrence of [legacyserver].[database], the chances of mistakes are very high.
You can create a synonym
CREATE SYNONYM [table] FOR [legacyserver].[database].[schema].[table]
When you query
SELECT * FROM table
it's actually fetching data from linked server instead of local database.
If want to change database, just drop synonym and create a new one with new database name.
DROP SYNONYM table;
CREATE SYNONYM [table] FOR [legacyserver].[anotherdatabase].[schema].[table]
Your query statement is unchanged.
EDIT: DROP and CREATE SYNONYM statement is a little misleading. You don't need to do it yourself. It's one time job in deployment. Just create a Post-Deployment script that creates all synonyms and parametrize linked server name and database names. Code like:
IF EXISTS (SELECT * FROM sys.synonyms WHERE name = 'table1')
BEGIN
DROP SYNONYM table1
END
EXEC('CREATE SYNONYM table1 FOR ' + '$(LinkedServerName).$(DBName).[dbo].[Table1]')
Note, it use SQLCMD syntax.
Ask operations to change parameter in different environments.

How can I create backup script from diagram in SQL Server?

I use SQL Server 2012 and SQL Server 2008 R2.
I create a script from all object (tables / trigger / stored procedure / function ...) in my database.
I generated this script from SQL Server Management Studio. I can recreate my database with this scrips on the other server. But I miss all diagrams of my database after run my script for create another database.
Therefore, I need create backup script from all diagrams that exist in my database.
I need execute this script on the destination database for recreating all my diagrams.
I found this Link. but i need some thinks that create all script (Insert Command) automatically.
I have found a reasonable solution. The problem is that Management Studio cannot display more that 65535 characters for Non-XML data, and cannot be set to display more than 65535.
See code for documentation :)
Backup script:
-- 1. Read from DB, using XML to workaround the 65535 character limit
declare #definition varbinary(max)
select #definition = definition from dbo.sysdiagrams where name = 'ReportingDBDiagram'
select
'0x' + cast('' as xml).value('xs:hexBinary(sql:variable("#definition") )', 'varchar(max)')
for xml path('')
-- 2. Open the result XML in Management Studio
-- 3. Copy the result
-- 4. Paste this in backup script for #definition variable
Restore script:
declare #definition varbinary(max)
set #definition = 0xD0CF -- Paste 0x0 value from Backup script
-- Create diagram using 'official' Stored Procedure
exec dbo.sp_creatediagram
#diagramname = 'ReportingDBDiagramCopy',
#owner_id = null,
#version = 1,
#definition = #definition
Scripting your database does not include diagrams as they are not server objects in the same way as a table or stored procedure; they exist as data in the sysdiagrams table.
A similar question on SO asked How do you migrate SQL Server Database Diagrams to another Database?
The accepted answer is to copy the contents of the sysdiagrams table to the new database, so you could include the table contents in your script. The answer with the most up-votes has a link to a way of scripting diagrams.
I've tried backing up and then restoring a database to the same server, deleting the diagram I had created (I only had one) and then running the following query:
INSERT INTO database2.dbo.sysdiagrams
(
NAME
,principal_id
,version
,DEFINITION
)
SELECT NAME
,principal_id
,version
,DEFINITION
FROM database1.dbo.sysdiagrams
The diagram was successfully restored, however I did do this on a restored backup, I should really test it with a new database generated from a script.
UPDATE:
I scripted a database and then created a new database from it. When trying to rebuild the diagrams using an INSERT statement I got the error
So although it seems possible it's not trivial to create diagrams in a new database created from a script. Go with the answer given regarding scripting diagrams and modify it for your own needs.
Perhaps you can investigate further and post your own answer :)
Here's a quick & dirty method I use. Since the query window won't display the full varbinary(max) value of the definition field, but the XML editor will, I output the rows to XML as follows:
Run the following query on the server/database that contains the diagrams:
SELECT 'INSERT sysdiagrams(name,principal_id,diagram_id,version,definition) VALUES('''+name+''','
+CONVERT(varchar(2),principal_id)+','+CONVERT(varchar(2),diagram_id)+','+CONVERT(varchar(2),version)+','
+'0x' + CAST('' as xml).value('xs:hexBinary(sql:column("definition"))','varchar(max)') +')'
FROM RCSQL_ClaimStatus.dbo.sysdiagrams
FOR XML PATH
Click on the generated link to open the XML result, and ctrl-a & ctrl-c to copy all rows generated.
Paste that output back into your query window. I usually paste it between a pair of IDENTITY_INSERT's like this:
--TRUNCATE TABLE sysdiagrams
SET IDENTITY_INSERT sysdiagrams ON;
<row>INSERT sysdiagrams(name,principal_id,diagram_id,version,definition) VALUES('ERD1',1,1,1,0xD0CF11E0A1B11AE100000...)</row>
<row>INSERT sysdiagrams(name,principal_id,diagram_id,version,definition) VALUES('ERD2',1,2,1,0xD0CF11E0A1B11AE100000...)</row>
<row>INSERT sysdiagrams(name,principal_id,diagram_id,version,definition) VALUES('ERD3',1,3,1,0xD0CF11E0A1B11AE100000...)</row>
SET IDENTITY_INSERT sysdiagrams OFF;
Remove the row & /row XML tags from your inserts, and run them on the target server. You can truncate the sysdiagrams table if you're replacing all values with new values.

Audit trigger in sql azure

I added a trigger to the table to copy the inserted data to an audit table.
I got all the column names of the table from INFORMATION_SCHEMA.
I used "SELECT * INTO #INSERTED FROM INSERTED" to copy inserted data to a temporary table.
Then used the following dynamic query to get the data from temporary table for each column.
SET #sqlText = N'SELECT ' + #ColName + ' FROM #INSERTED'
where #ColName is the column name.
It was working fine with sql server 2008.
Now we moved to sql azure. select into is not supported in sql azure. I cannot create a temporary table and then use insert on it, as my table contains over 70 columns and also, I cannot use INSERTED table for a dynamic query.
So, please suggest any solution\workaround for it.
SQL Azure V11 doesn't support select into. Please upgrade your server to SQL DB v12 and you should be able to do this.

Resources