How to select data from another sql server server tables in sql script? - sql

I want to know how to query data from another SQL Server instances' tables in SQL script.
I am writing sql script running on 127.0.0.1\SQLINSTANCE1 but inside the script there is going to select data from 127.0.0.2\SQLINSTANCE2 then return the result data as part of calculation.
After googled, there seems uses the sp_addlinkedserver and sp_addlinkedsrvlogin stored procedures for doing that, but unfortunately there is no complete sample working.
I have some work here but not working as expected. For example, when it was executed once more then there would pop up some error like the server already linked. But how I can execute this script for linking the server and then abandoning it?
DECLARE #remoteserver VARCHAR = '127.0.0.2\SQLINSTANCE2';
EXEC master.sys.sp_addlinkedserver #server = #remoteserver
, #srvproduct = 'SQL Server';
EXEC master.sys.sp_addlinkedsrvlogin #rmtsrvname = #remoteserver
, #useself = 'false'
, #locallogin = NULL
, #rmtuser = 'sa'
, #rmtpassword = 'password';
To the other side, how can I create an alias for this ugly remoteserver name?
I rather to use some elegant name like RS in select * from [RS].[db].[dbo].[table]

You can indeed use the
OPENDATASOURCE
or
OPENROWSET
Note that you have to turn on the ad hoc distributed queries option:
sp_configure 'show advanced options', 1;
RECONFIGURE;
sp_configure 'Ad Hoc Distributed Queries', 1;
RECONFIGURE;
GO

You can use OPENROWSET so you won't have to make and delete a linked server.

Related

Error while executing xp_readerrorlog using OPENROWSET in SQL Server - querying remote data sources

Can you please help me to fix this query?
SELECT
FROM OPENROWSET('SQLNCLI',
'Server=.;Trusted_Connection=Yes;',
'SET FMTONLY OFF;EXEC master.sys.xp_readerrorlog')
I get this error:
Msg 11519, Level 16, State 1, Procedure sys.sp_describe_first_result_set, Line 1 [Batch Start Line 12]
The metadata could not be determined because statement 'EXEC master.sys.xp_readerrorlog' invokes an extended stored procedure.
I have enabled Ad-Hoc Distributed Queries as well by using below query but getting same error.
EXEC sp_configure 'show advanced options', 1;
RECONFIGURE;
EXEC sp_configure 'Ad Hoc Distributed Queries', 1;
RECONFIGURE;
GO
You cannot use OPENROWSET for an extended stored procedure. You could create a linked server
EXEC {Your Linked Server Name}.master.sys.xp_readerrorlog;
But you say you have 120 instances. (Quite why you don't have management software for so many, is another question...) So you are better off using Powershell to do this. For example
Get-SqlErrorLog
-Since LastMonth
-ServerInstance "your","Server","Instances","Here"
You would probably want other code to filter and group the results, but you haven't shown what you want.
For example you could do something like this
Get-Content "ServerInstances.txt"
| Get-SqlErrorLog -After "2022-09-16 10:00:00"
| Where Source -eq "Backup"

Command to read/import .dbf files from local system into SQL Server 2016 64 bit

I am trying to import .dbf files into SQL Server 2016 64bit. For this I installed Microsoft Visual FoxPro. Below setup works for 32bit version of SQL Server but not to 64bit. I also tried changing the driver's name eg: Microsoft.Jet.OLEDB.4.0, Microsoft.ACE.OLEDB.16.0, etc. but no luck.
USE [master]
GO
EXEC sp_configure 'show advanced options', 1
RECONFIGURE
GO
EXEC sp_configure 'ad hoc distributed queries', 1
RECONFIGURE
GO
USE [master]
GO
EXEC master.dbo.sp_MSset_oledb_prop N'VFPOLEDB', N'AllowInProcess', 1
GO
And then,
DECLARE #sql AS NVARCHAR(200),
#path AS NVARCHAR(200),
#table AS NVARCHAR(200)
SET #path = 'C:\Users\sid\Downloads\VPF\'
SET #table = 'dmfiles'
SET #sql = 'Select * from openrowset(''VFPOLEDB'','''+#path+''';'''';'''',''select * from '+#table+'.dbf'')'
EXEC sp_executesql #sql
Also tried creating a Linked server type of cmd:
SELECT *
FROM OPENROWSET ('MICROSOFT.ACE.OLEDB.12.0','dBase
5.0;HDR=YES;IMEX=2;DATABASE=\Dbf Directory\','SELECT * FROM dbf_filename.dbf')
When I either try to open Linked server, run any command, SQL Server just says executing and never shows any result nor throws error.
I tried using DBF Viewer 2000 to convert .dbf to .sql and ran them against a DB but, running above SQL (if worked fine) would be great for my automation script.
Help is much appreciated!

Localdb linked servers

I'm trying to replicate a production environment locally and the production database uses a linked server. I've been able to create multiple instances of localdb; is it possible to create a linkedserver between localdb instances? If not, what other options do I have available (ideally without having to use a full sql instance).
Not sure if it's bad form to answer your own question but in case anyone else has the same issue in the future, it turns out it is possible and pretty straight forward. Once you've created your new instance of localdb, use this:
USE master
IF EXISTS(SELECT * from sys.servers WHERE name = N'{serverName}')
BEGIN
DECLARE #serverId INT
SELECT #serverId = server_id FROM sys.servers WHERE name = N'{serverName}'
IF EXISTS(SELECT * FROM sys.linked_logins WHERE server_id = #serverId)
BEGIN
EXEC sp_droplinkedsrvlogin '{serverName}', null
END
EXEC sp_dropserver '{serverName}'
END
EXEC sp_addlinkedserver
#server=N'{serverName}',
#provider=N'SQLNCLI',
#srvproduct=N'',
#datasrc=N'{dataSource}';
EXEC sp_addlinkedsrvlogin
#rmtsrvname=N'{serverName}',
#useself='true'
To expand on Dave's auto-answer a little...
If the remote database has not been attached to its instance yet, it will be necessary to include additional connection details in the Provider String argument of sp_addlinked server.
EXEC sp_addlinkedserver
#server=N'{serverName}',
#provider=N'SQLNCLI',
#srvproduct=N'',
#datasrc=N'{dataSource}'
#provstr=N'{providerString}';
In my case I used:
{dataSource} = (LocalDB)\MSSQLLocalDB
{providerString} = AttachDbFileName=C:\Temp\Test.mdf;Integrated Security=True

error while executing excel file in sql server 2008

I have tried the following query in a SQL query
SELECT * FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0', 'Excel 12.0;Database=c:\generalholiday.xls','select * from [sheet1$]')
The following error is happened:
OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)"
returned message "The Microsoft Access database engine could not find
the object 'sheet1$'. Make sure the object exists and that you spell
its name and the path name correctly. If 'sheet1$' is not a local
object, check your network connection or contact the server
administrator.". Msg 7350, Level 16, State 2, Line 1 Cannot get the
column information from OLE DB provider "Microsoft.ACE.OLEDB.12.0" for
linked server "(null)".
Actually I searched lot of answered based on this queries. But I did not get reliable result for me.
What I have done so far,
I installed access database engine 64 bit, and run the following queries
EXEC sp_configure 'show advanced options', 1
RECONFIGURE
GO
EXEC sp_configure 'ad hoc distributed queries', 1
RECONFIGURE
GO
EXEC master.dbo.sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'AllowInProcess', 1
GO
EXEC master.dbo.sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'DynamicParameters', 1
GO
but still the above error is occurred. it is headache for me a full day to find this solution.
Please give me solution for this problem.
I am using SQL Server 2008 (64 bit) and MS Office 32 bit
I remember having similar errors setting this up initially on my server and I can't remember which bit solved it, but I believe it may have been running the following:
USE [master]
GO
EXEC master . dbo. sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0' , N'AllowInProcess' , 1
GO
EXEC master . dbo. sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0' , N'DynamicParameters' , 1
GO
Also, if I remember correctly the Excel file can't be open elsewhere when you try to query it.

How to run a stored procedure when SQL Server Express Edition starts?

How is it possible to run a stored procedure when SQL Server Express Edition starts?
Use the system stored procedure sp_procoption to define the stored procedure you wish to be executed at SQL Server Service startup.
exec sp_procoption
#ProcName = 'procedureName',
#OptionName = 'startup',
#OptionValue = 'true'
USE master;
GO
-- first set the server to show advanced options
EXEC sp_configure 'show advanced option', '1';
RECONFIGURE
-- then set the scan for startup procs to 1
EXEC sp_configure 'scan for startup procs', '1';
RECONFIGURE
IF OBJECT_ID('spTest') IS NOT NULL
DROP PROC spTest
GO
-- crate a test stored procedure
CREATE PROC spTest
AS
-- just create a sample database
EXEC('CREATE database db1')
GO
-- set it to run at sql server start-up
exec sp_procoption N'spTest', 'startup', 'on'