SlideShare uma empresa Scribd logo
1 de 6
Baixar para ler offline
How do I... Query foreign data using SQL Server's linked servers? | TechRepublic



   ZDNet Asia    SmartPlanet     TechRepublic                                                                                     Log In   Join TechRepublic   FAQ   Go Pro!




                                                     Blogs      Downloads          Newsletters   Galleries      Q&A     Discussions        News
                                                Research Library


     IT Management             Development           IT Support         Data Center        Networks        Security




     Home / Blogs / The Enterprise Cloud                                                    Follow this blog:

     The Enterprise Cloud


     How do I... Query foreign data
     using SQL Server's linked
     servers?
     By Susan Harkins
     July 2, 2007, 12:47 PM PDT

     This information is also available as a PDF download.

     If you have a magic wand or a special relationship with some data fairy, all of your data is in the
     same database on the same server. Most of us aren’t that lucky. Sometimes, the data we need is
     a non-database format or resides on a different server. SQL Server is flexible enough to offer a
     number of ways to get the data you need. One of the easiest methods is to directly link to the data
     via a linked server. (Microsoft SQL Server 2005 Express Edition also supports linked servers.)




     What’s a linked server?
     A linked server is simply a connection to an Object Linking and Embedding Database (OLEDB)
     data source. Technically, OLEDB is a Microsoft standard API for retrieving data from a wide variety
     of data. If that’s clear as mud, don’t worry. The good news is that it’s flexible enough to link to
     database and non-database formats, such as a spreadsheet or e-mail client. Simply put, SQL
     Server supports any OLEDB provider (also called a driver). There’s more good news: You can use
     Transact-SQL or Management Studio to make the connection. After you create a linked server,
     SQL Server can log into another database server. That means you can run queries on a remote
     server. You have two types of linked server queries at your disposal: ad hoc and permanent.

     Ad hoc links
     Technically, you won’t use the term linked server to identify an ad hoc query. That term really
     refers to a SQL Server object. However, you will often see the term used to refer to an ad hoc
     linked query. An ad hoc query opens and closes the connection. A permanent linked server is
     always available. Use OPENROWSET for infrequent linked tasks, using the following syntax:

     OPENROWSET('providername', 'datasource', 'username', 'password', object)

     An OPENROWSET link consumes less space in your database. Use valid Transact-SQL
     statements to manipulate the retrieved data. The arguments are self-explanatory, but remember
     that datasource is the source’s full path, not just a filename. In addition, the provider provides the
     instructions that SQL Server needs to get in and grab data. They’re specific to the foreign software
     you’re accessing.

     Now, let’s look at a simple ad hock query that selects all the records from the Employees table in


http://www.techrepublic.com/blog/datacenter/how-do-i-query-foreign-data-using-sql-servers-linked-servers/133[08/29/2012 3:00:28 PM]
How do I... Query foreign data using SQL Server's linked servers? | TechRepublic


     the Microsoft Access sample database, Northwind:

     SELECT *

     FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',

     'C:Program FilesMicrosoft OfficeOffice11Office11SamplesNorthwind.mdb';

     'admin';'', Employees)

     AS EmployeesFromAccess

     Figure A shows the quickly retrieved results, which depend on the user (admin) having the
     appropriate permissions. (If you want to run this query, be sure to update the path to
     Northwind.mdb to accommodate your system.) The provider string is specific to the data engine,
     Jet. The AS keyword provides a name for the new table inside SQL Server.

     Figure A: Use OPENROWSET for infrequent queries of foreign data
     (Express edition).




     If the ad hoc query returns an error, you probably need to enable the ad hoc query feature. (SQL
     Server disables it by default.) To enable ad hoc queries, run the SQL Server Configuration
     Manager (the SQL Server Surface Area Configuration utility in the Express edition). Click the
     Surface Area Configuration For Features link and check the Enable OPENROWSET And
     OPENDATASOURCE Support option. Then, click OK and close the utility. Alternatively, run the
     sp_configure stored procedure.

     Permanent links
     SQL Server’s linked server object creates a permanent link to a remote server. When the user logs
     in, SQL Server also logs into the remote server. The first step to retrieving foreign data via a linked
     server is to let SQL Server know that you plan to talk to another source (server). To do so,
     execute SQL Server’s sp_addlinkedserver stored procedure, using the following syntax:

     sp_addlinkedserver server, productname, provider, datasource, location, providerstring, catalog

     Refer to Table A for an explanation of each of the procedure’s arguments. Notice that a few of
     the arguments are limited to code.

     Table A: sp_addlinkedserver stored procedure arguments

                                                                                                Parameter
      Argument             Explanation                  Default        Management Studio
                                                                                                Constant
                           The local name of the
      server               linked server you’re         None           Linked Server            @server
                           creating
                           The product name of
                           the OLEDB data
      productname                                       NULL           Product Name             @srvproduct
                           source you’re adding
                           as a linked server
                           The source’s unique
      provider                                          NULL           Provider Name            @provider
                           OLEDB identifier




http://www.techrepublic.com/blog/datacenter/how-do-i-query-foreign-data-using-sql-servers-linked-servers/133[08/29/2012 3:00:28 PM]
How do I... Query foreign data using SQL Server's linked servers? | TechRepublic

                           The name of the data
      datasource                                        NULL           Data Source              @datasrc
                           source
                           The location of the
      location                                          NULL           N/A                      @location
                           linked source file
                           The OLEDB string
      providerstring       that identifies the          NULL           N/A                      @provstr
                           source
                           Catalog used with the
      catalog                                           NULL           N/A                      @catalog
                           connection

     The arguments aren’t optional, but you won’t use them all together, which explains the NULL
     value defaults. The provider determines which arguments you need. When using SQL Server, you
     need only the first two arguments.

     Now, let’s suppose you want to create a permanent link to another SQL Server database on the
     Human Resources server. To do so, you’d use the following statement:

     EXEC sp_addlinkedserver @server = 'EmployeeStats',

     @provider = 'SQL Server',

     @datasrc = 'Human Resources'

     The linked server’s name, EmployeeStats, is a string that you provide to represent the server. It
     doesn’t exist until you name and create it. The following syntax statements represent the creation
     of a linked server to several common data sources:

     Microsoft Access

     EXEC sp_addlinkedserver @server = 'NorthwindDemo',

     @srvproduct = 'Microsoft.Jet.OLEDB.4.0',

     @provider = 'Microsoft.Jet.OLEDB.4.0',

     @datasrc = 'C:LinkedNorthwind.mdb'

     Microsoft Excel

     EXEC sp_addlinkedserver @server = 'ExcelEmployeeData',

     @srvproduct = 'Microsoft.Jet.OLEDB.4.0',

     @provider = 'Microsoft.Jet.OLEDB.4.0',

     @datasrc = 'C:LinkedEmployees.xls'

     Oracle

     EXEC sp_addlinkedserver @server = 'OracleDemo',

     @srvproduct = 'Oracle',

     @provider = 'MSDAORA',

     @datasrc = 'OracleAlias'

     Oracle is a bit different because you must create an alias that points to the Oracle server rather
     than specify an actual file (@datasrc). Every situation is different. Your best defense is experience
     and an informed technical staff.

     SQL Server throws a monkey wrench into the works because it doesn’t return an error if you use
     the wrong syntax. Instead, any attempt to use the linked server simply fails, but the failure might
     not be obvious. My best recommendation is to test a query that you know should return data. If
     you get nothing, you know the linked server isn’t really connecting and the problem is most likely
     the arguments you fed sp_addlinkedserver to create the linked server.

     Using Management Studio
     Using Management Studio to create a linked server is even easier. Look for the Linked Server
     folder in the Server Objects or Security folder (depending on which version you’re using). The
     good news is that Management Studio simplifies the process. You still have to enter the product
     name, provider, and path to the file. If an option is disabled and you need it, as shown in Figure
     B, you must turn to sp_addlinkedserver. In this case, Access doesn’t support the Location and



http://www.techrepublic.com/blog/datacenter/how-do-i-query-foreign-data-using-sql-servers-linked-servers/133[08/29/2012 3:00:28 PM]
How do I... Query foreign data using SQL Server's linked servers? | TechRepublic

     Catalog options, so Management Studio disables them.

     Figure B: Management Studio doesn’t support all of the options for
     every provider (Express edition).




     Retrieving data
     Once the linked server exists, you can use it to query data, just as if you were working with SQL
     Server tables. Figure C shows the result of retrieving all the Employee records from Northwind
     using the SQL statement via a linked server named NorthwindDemo:

     SELECT * FROM NorthwindDemo...Employees

     The statement identifies the remote server and the table from which you’re retrieving data.

     Figure C: Retrieve Access data via a linked server (Express edition).




     When querying data via the ExcelData linked server, include a named range as follows:

     SELECT *

     FROM ExcelData, Employees




http://www.techrepublic.com/blog/datacenter/how-do-i-query-foreign-data-using-sql-servers-linked-servers/133[08/29/2012 3:00:28 PM]
How do I... Query foreign data using SQL Server's linked servers? | TechRepublic


     One or two gotchas
     The biggest catch to all this simplicity is, as always, security. If you’re working with Windows
     Authentication, the system accommodates well. If the user has the appropriate permissions for the
     servers and data sources, linked queries will work.

     If you have users outside the Windows Authentication environment, you can use a linked login.
     Create a standard login and assign the appropriate permissions on the remote server. Then, from
     the sending server, use sp_addlinkedsrvlogin to map local logins to the remote logins using the
     following syntax:

     sp_addlinkedsrvlogin remoteservername, useseif, locallogin, remoteuser, remotepassword

     For instance, after executing the following statement, the user logging in locally as Susan1 with the
     password rabbitX will have access to data via the NorthwindDemo linked server if you’ve correctly
     mapped the logins:

     EXEC sp_addlinkedsrvlogin @rmtsrvname = 'NorthwindDemo',

     @useseif = FALSE,

     @locallogin = 'NULL',

     @rmtuser = 'Susan1',

     @rmtpassword = 'rabbitX'

     Table B describes the sp_addlinkedsrvlogin arguments.

     Table B: sp_addlinkedsrvlogin arguments

      Argument                     Explanation                                     Constant
      server                       The server’s name                               @rmtsrvname

                                   Use with Windows Integrated Security to
      useseif                                                                      @useseif
                                   authorize users
      locallogin                   Your local login                                @locallogin
      remoteuser                   The user name                                   @rmtuser
      remotepassword               The password                                    @rmtpassword

     Another catch is the ever-growing, ever-changing list of providers and connection strings that
     you’ll need. You’ll find a comprehensive list of provider strings at ConnectionStrings.com.

     Provider names aren’t intuitive either. Table C lists some common provider names.

     Table C: Provider names

      SQL Server                                               SQLNCLI

      Oracle                                                   MSDAORA
      Oracle, version 8 and later                              OraOLEDB.Oracle
      Access/Jet and Excel                                     Microsoft.Jet.OLEDB.4.0
      ODBC data source                                         MSDASQL
      IBM DB2 Database                                         DB2OLEDB




     Susan Sales Harkins is an independent consultant and the author of several articles and books on
     database technologies. Her most recent book is Mastering Microsoft SQL Server 2005 Express,
     with Mike Gunderloy, published by Sybex. Other collaborations with Gunderloy are Automating
     Microsoft Access 2003 with VBA, Upgrader’s Guide to Microsoft Office System 2003, ICDL Exam
     Cram 2, and Absolute Beginner’s Guide to Microsoft Access 2003, all published by Que. Currently,
     Susan volunteers as the Publications Director for Database Advisors. You can reach her at
     ssharkins@setel.com.


     Get IT Tips, news, and reviews delivered directly to your inbox by subscribing to TechRepublic’s free



http://www.techrepublic.com/blog/datacenter/how-do-i-query-foreign-data-using-sql-servers-linked-servers/133[08/29/2012 3:00:28 PM]
How do I... Query foreign data using SQL Server's linked servers? | TechRepublic

     newsletters.




                    Restore your SQL Server                         Solid state drive storage:
                    database using transaction                      Good for the enterprise?
                    logs




          0           Join the conversation!                                               Add Your Opinion
      Comments        Follow via:



       Staff Picks     Top Rated       Most Recent        My Contacts                             See All Comments



        Log in to display your contacts' posts.

        Once logged in, adding contacts is simple. Just mouse over any member's photo or click
        any member's name then click the "Follow" button. You can easily manage your contacts
        within your account contacts page.



                                                   See all comments



     Join the TechRepublic Community and join the conversation! Signing-up is
     free and quick, Do it now, we want to hear your opinion.

       Join         Login




http://www.techrepublic.com/blog/datacenter/how-do-i-query-foreign-data-using-sql-servers-linked-servers/133[08/29/2012 3:00:28 PM]

Mais conteúdo relacionado

Mais procurados

.NET Core, ASP.NET Core Course, Session 15
.NET Core, ASP.NET Core Course, Session 15.NET Core, ASP.NET Core Course, Session 15
.NET Core, ASP.NET Core Course, Session 15aminmesbahi
 
How to execute an oracle stored procedure with nested table as a parameter fr...
How to execute an oracle stored procedure with nested table as a parameter fr...How to execute an oracle stored procedure with nested table as a parameter fr...
How to execute an oracle stored procedure with nested table as a parameter fr...Priyobroto Ghosh (Mule ESB Certified)
 
Recent Additions to Lucene Arsenal
Recent Additions to Lucene ArsenalRecent Additions to Lucene Arsenal
Recent Additions to Lucene Arsenallucenerevolution
 
MySQL Indexes and Histograms - RMOUG Training Days 2022
MySQL Indexes and Histograms - RMOUG Training Days 2022MySQL Indexes and Histograms - RMOUG Training Days 2022
MySQL Indexes and Histograms - RMOUG Training Days 2022Dave Stokes
 
Java Web Programming Using Cloud Platform: Module 3
Java Web Programming Using Cloud Platform: Module 3Java Web Programming Using Cloud Platform: Module 3
Java Web Programming Using Cloud Platform: Module 3IMC Institute
 
Lucene Introduction
Lucene IntroductionLucene Introduction
Lucene Introductionotisg
 
ASP.NET Session 11 12
ASP.NET Session 11 12ASP.NET Session 11 12
ASP.NET Session 11 12Sisir Ghosh
 
Find Anything In Your APEX App - Fuzzy Search with Oracle Text
Find Anything In Your APEX App - Fuzzy Search with Oracle TextFind Anything In Your APEX App - Fuzzy Search with Oracle Text
Find Anything In Your APEX App - Fuzzy Search with Oracle TextCarsten Czarski
 
Oracle Developer Live: Deploying MySQL InnoDB Cluster on OCI with Terraform
Oracle Developer Live: Deploying MySQL InnoDB Cluster on OCI with TerraformOracle Developer Live: Deploying MySQL InnoDB Cluster on OCI with Terraform
Oracle Developer Live: Deploying MySQL InnoDB Cluster on OCI with TerraformFrederic Descamps
 
Tutorial on developing a Solr search component plugin
Tutorial on developing a Solr search component pluginTutorial on developing a Solr search component plugin
Tutorial on developing a Solr search component pluginsearchbox-com
 
Oracle Text in APEX
Oracle Text in APEXOracle Text in APEX
Oracle Text in APEXScott Wesley
 
Spring review_for Semester II of Year 4
Spring review_for Semester II of Year 4Spring review_for Semester II of Year 4
Spring review_for Semester II of Year 4than sare
 
Ebs dba con4696_pdf_4696_0001
Ebs dba con4696_pdf_4696_0001Ebs dba con4696_pdf_4696_0001
Ebs dba con4696_pdf_4696_0001jucaab
 
Installing ingres enterprise access in a system which already has an ingres i...
Installing ingres enterprise access in a system which already has an ingres i...Installing ingres enterprise access in a system which already has an ingres i...
Installing ingres enterprise access in a system which already has an ingres i...malu42
 

Mais procurados (20)

PHP Oracle
PHP OraclePHP Oracle
PHP Oracle
 
.NET Core, ASP.NET Core Course, Session 15
.NET Core, ASP.NET Core Course, Session 15.NET Core, ASP.NET Core Course, Session 15
.NET Core, ASP.NET Core Course, Session 15
 
Servlet unit 2
Servlet unit 2 Servlet unit 2
Servlet unit 2
 
6 database
6 database 6 database
6 database
 
How to execute an oracle stored procedure with nested table as a parameter fr...
How to execute an oracle stored procedure with nested table as a parameter fr...How to execute an oracle stored procedure with nested table as a parameter fr...
How to execute an oracle stored procedure with nested table as a parameter fr...
 
MySQL Quick Dive
MySQL Quick DiveMySQL Quick Dive
MySQL Quick Dive
 
Recent Additions to Lucene Arsenal
Recent Additions to Lucene ArsenalRecent Additions to Lucene Arsenal
Recent Additions to Lucene Arsenal
 
MySQL Indexes and Histograms - RMOUG Training Days 2022
MySQL Indexes and Histograms - RMOUG Training Days 2022MySQL Indexes and Histograms - RMOUG Training Days 2022
MySQL Indexes and Histograms - RMOUG Training Days 2022
 
Java Web Programming Using Cloud Platform: Module 3
Java Web Programming Using Cloud Platform: Module 3Java Web Programming Using Cloud Platform: Module 3
Java Web Programming Using Cloud Platform: Module 3
 
Lucene Introduction
Lucene IntroductionLucene Introduction
Lucene Introduction
 
ASP.NET Session 11 12
ASP.NET Session 11 12ASP.NET Session 11 12
ASP.NET Session 11 12
 
Spring jdbc dao
Spring jdbc daoSpring jdbc dao
Spring jdbc dao
 
Find Anything In Your APEX App - Fuzzy Search with Oracle Text
Find Anything In Your APEX App - Fuzzy Search with Oracle TextFind Anything In Your APEX App - Fuzzy Search with Oracle Text
Find Anything In Your APEX App - Fuzzy Search with Oracle Text
 
Jdbc sasidhar
Jdbc  sasidharJdbc  sasidhar
Jdbc sasidhar
 
Oracle Developer Live: Deploying MySQL InnoDB Cluster on OCI with Terraform
Oracle Developer Live: Deploying MySQL InnoDB Cluster on OCI with TerraformOracle Developer Live: Deploying MySQL InnoDB Cluster on OCI with Terraform
Oracle Developer Live: Deploying MySQL InnoDB Cluster on OCI with Terraform
 
Tutorial on developing a Solr search component plugin
Tutorial on developing a Solr search component pluginTutorial on developing a Solr search component plugin
Tutorial on developing a Solr search component plugin
 
Oracle Text in APEX
Oracle Text in APEXOracle Text in APEX
Oracle Text in APEX
 
Spring review_for Semester II of Year 4
Spring review_for Semester II of Year 4Spring review_for Semester II of Year 4
Spring review_for Semester II of Year 4
 
Ebs dba con4696_pdf_4696_0001
Ebs dba con4696_pdf_4696_0001Ebs dba con4696_pdf_4696_0001
Ebs dba con4696_pdf_4696_0001
 
Installing ingres enterprise access in a system which already has an ingres i...
Installing ingres enterprise access in a system which already has an ingres i...Installing ingres enterprise access in a system which already has an ingres i...
Installing ingres enterprise access in a system which already has an ingres i...
 

Semelhante a How do i... query foreign data using sql server's linked servers tech_repu

Ado dot net complete meterial (1)
Ado dot net complete meterial (1)Ado dot net complete meterial (1)
Ado dot net complete meterial (1)Mubarak Hussain
 
Ch06 ado.net fundamentals
Ch06 ado.net fundamentalsCh06 ado.net fundamentals
Ch06 ado.net fundamentalsMadhuri Kavade
 
Introduction to sql server
Introduction to sql serverIntroduction to sql server
Introduction to sql serverVinay Thota
 
Qtp connect to an oracle database database - database skill
Qtp connect to an oracle database   database - database skillQtp connect to an oracle database   database - database skill
Qtp connect to an oracle database database - database skillsiva1991
 
Introduction to ado
Introduction to adoIntroduction to ado
Introduction to adoHarman Bajwa
 
5\9 SSIS 2008R2_Training - DataFlow Basics
5\9 SSIS 2008R2_Training - DataFlow Basics5\9 SSIS 2008R2_Training - DataFlow Basics
5\9 SSIS 2008R2_Training - DataFlow BasicsPramod Singla
 
SQLSaturday#290_Kiev_WindowsAzureDatabaseForBeginners
SQLSaturday#290_Kiev_WindowsAzureDatabaseForBeginnersSQLSaturday#290_Kiev_WindowsAzureDatabaseForBeginners
SQLSaturday#290_Kiev_WindowsAzureDatabaseForBeginnersTobias Koprowski
 
Ob loading data_oracle
Ob loading data_oracleOb loading data_oracle
Ob loading data_oracleSteve Xu
 
Get database properties using power shell in sql server 2008 techrepublic
Get database properties using power shell in sql server 2008   techrepublicGet database properties using power shell in sql server 2008   techrepublic
Get database properties using power shell in sql server 2008 techrepublicKaing Menglieng
 
Sql interview question part 6
Sql interview question part 6Sql interview question part 6
Sql interview question part 6kaashiv1
 
Sql interview-question-part-6
Sql interview-question-part-6Sql interview-question-part-6
Sql interview-question-part-6kaashiv1
 

Semelhante a How do i... query foreign data using sql server's linked servers tech_repu (20)

Ado dot net complete meterial (1)
Ado dot net complete meterial (1)Ado dot net complete meterial (1)
Ado dot net complete meterial (1)
 
Ado.net
Ado.netAdo.net
Ado.net
 
Ch06 ado.net fundamentals
Ch06 ado.net fundamentalsCh06 ado.net fundamentals
Ch06 ado.net fundamentals
 
Data virtualization using polybase
Data virtualization using polybaseData virtualization using polybase
Data virtualization using polybase
 
Introduction to sql server
Introduction to sql serverIntroduction to sql server
Introduction to sql server
 
Sql Sever Presentation.pptx
Sql Sever Presentation.pptxSql Sever Presentation.pptx
Sql Sever Presentation.pptx
 
Qtp connect to an oracle database database - database skill
Qtp connect to an oracle database   database - database skillQtp connect to an oracle database   database - database skill
Qtp connect to an oracle database database - database skill
 
PPT temp.pptx
PPT temp.pptxPPT temp.pptx
PPT temp.pptx
 
Introduction to ado
Introduction to adoIntroduction to ado
Introduction to ado
 
Jdbc
JdbcJdbc
Jdbc
 
5\9 SSIS 2008R2_Training - DataFlow Basics
5\9 SSIS 2008R2_Training - DataFlow Basics5\9 SSIS 2008R2_Training - DataFlow Basics
5\9 SSIS 2008R2_Training - DataFlow Basics
 
Ado
AdoAdo
Ado
 
Ebook11
Ebook11Ebook11
Ebook11
 
Ado.Net Tutorial
Ado.Net TutorialAdo.Net Tutorial
Ado.Net Tutorial
 
SQLSaturday#290_Kiev_WindowsAzureDatabaseForBeginners
SQLSaturday#290_Kiev_WindowsAzureDatabaseForBeginnersSQLSaturday#290_Kiev_WindowsAzureDatabaseForBeginners
SQLSaturday#290_Kiev_WindowsAzureDatabaseForBeginners
 
Ob loading data_oracle
Ob loading data_oracleOb loading data_oracle
Ob loading data_oracle
 
Get database properties using power shell in sql server 2008 techrepublic
Get database properties using power shell in sql server 2008   techrepublicGet database properties using power shell in sql server 2008   techrepublic
Get database properties using power shell in sql server 2008 techrepublic
 
Sql interview question part 6
Sql interview question part 6Sql interview question part 6
Sql interview question part 6
 
Ebook6
Ebook6Ebook6
Ebook6
 
Sql interview-question-part-6
Sql interview-question-part-6Sql interview-question-part-6
Sql interview-question-part-6
 

Mais de Kaing Menglieng

What is your sql server backup strategy tech_republic
What is your sql server backup strategy    tech_republicWhat is your sql server backup strategy    tech_republic
What is your sql server backup strategy tech_republicKaing Menglieng
 
Using sql server 2008's merge statement tech republic
Using sql server 2008's merge statement   tech republicUsing sql server 2008's merge statement   tech republic
Using sql server 2008's merge statement tech republicKaing Menglieng
 
Using grouping sets in sql server 2008 tech republic
Using grouping sets in sql server 2008   tech republicUsing grouping sets in sql server 2008   tech republic
Using grouping sets in sql server 2008 tech republicKaing Menglieng
 
Understand when to use user defined functions in sql server tech-republic
Understand when to use user defined functions in sql server   tech-republicUnderstand when to use user defined functions in sql server   tech-republic
Understand when to use user defined functions in sql server tech-republicKaing Menglieng
 
Sql server indexed views speed up your select queries part 1 - code-projec
Sql server indexed views   speed up your select queries  part 1 - code-projecSql server indexed views   speed up your select queries  part 1 - code-projec
Sql server indexed views speed up your select queries part 1 - code-projecKaing Menglieng
 
Sql server – query optimization – remove bookmark lookup – remove rid lookup
Sql server – query optimization – remove bookmark lookup – remove rid lookupSql server – query optimization – remove bookmark lookup – remove rid lookup
Sql server – query optimization – remove bookmark lookup – remove rid lookupKaing Menglieng
 
Sql server common interview questions and answers
Sql server   common interview questions and answersSql server   common interview questions and answers
Sql server common interview questions and answersKaing Menglieng
 
Sql server common interview questions and answers page 6
Sql server   common interview questions and answers page 6Sql server   common interview questions and answers page 6
Sql server common interview questions and answers page 6Kaing Menglieng
 
Sql server common interview questions and answers page 5
Sql server   common interview questions and answers page 5Sql server   common interview questions and answers page 5
Sql server common interview questions and answers page 5Kaing Menglieng
 
Sql server common interview questions and answers page 4
Sql server   common interview questions and answers page 4Sql server   common interview questions and answers page 4
Sql server common interview questions and answers page 4Kaing Menglieng
 
Sql server common interview questions and answers page 2
Sql server   common interview questions and answers page 2Sql server   common interview questions and answers page 2
Sql server common interview questions and answers page 2Kaing Menglieng
 
Sql server – 2008 – hardware and software requirements for installing sql se
Sql server – 2008 – hardware and software requirements for installing sql seSql server – 2008 – hardware and software requirements for installing sql se
Sql server – 2008 – hardware and software requirements for installing sql seKaing Menglieng
 
Speeding up queries with semi joins and anti-joins
Speeding up queries with semi joins and anti-joinsSpeeding up queries with semi joins and anti-joins
Speeding up queries with semi joins and anti-joinsKaing Menglieng
 
Speed up sql server apps - visual studio magazine
Speed up sql server apps  - visual studio magazineSpeed up sql server apps  - visual studio magazine
Speed up sql server apps - visual studio magazineKaing Menglieng
 
See sql server graphical execution plans in action tech republic
See sql server graphical execution plans in action   tech republicSee sql server graphical execution plans in action   tech republic
See sql server graphical execution plans in action tech republicKaing Menglieng
 
Reviewing sql server permissions tech republic
Reviewing sql server permissions   tech republicReviewing sql server permissions   tech republic
Reviewing sql server permissions tech republicKaing Menglieng
 
Query optimization how to search millions of record in sql table faster -
Query optimization   how to search millions of record in sql table faster  -Query optimization   how to search millions of record in sql table faster  -
Query optimization how to search millions of record in sql table faster -Kaing Menglieng
 
Optimize sql server queries with these advanced tuning techniques tech repu
Optimize sql server queries with these advanced tuning techniques   tech repuOptimize sql server queries with these advanced tuning techniques   tech repu
Optimize sql server queries with these advanced tuning techniques tech repuKaing Menglieng
 
New date datatypes in sql server 2008 tech republic
New date datatypes in sql server 2008   tech republicNew date datatypes in sql server 2008   tech republic
New date datatypes in sql server 2008 tech republicKaing Menglieng
 

Mais de Kaing Menglieng (20)

What is your sql server backup strategy tech_republic
What is your sql server backup strategy    tech_republicWhat is your sql server backup strategy    tech_republic
What is your sql server backup strategy tech_republic
 
Using sql server 2008's merge statement tech republic
Using sql server 2008's merge statement   tech republicUsing sql server 2008's merge statement   tech republic
Using sql server 2008's merge statement tech republic
 
Using grouping sets in sql server 2008 tech republic
Using grouping sets in sql server 2008   tech republicUsing grouping sets in sql server 2008   tech republic
Using grouping sets in sql server 2008 tech republic
 
Understand when to use user defined functions in sql server tech-republic
Understand when to use user defined functions in sql server   tech-republicUnderstand when to use user defined functions in sql server   tech-republic
Understand when to use user defined functions in sql server tech-republic
 
Sql server indexed views speed up your select queries part 1 - code-projec
Sql server indexed views   speed up your select queries  part 1 - code-projecSql server indexed views   speed up your select queries  part 1 - code-projec
Sql server indexed views speed up your select queries part 1 - code-projec
 
Sql server – query optimization – remove bookmark lookup – remove rid lookup
Sql server – query optimization – remove bookmark lookup – remove rid lookupSql server – query optimization – remove bookmark lookup – remove rid lookup
Sql server – query optimization – remove bookmark lookup – remove rid lookup
 
Sql server common interview questions and answers
Sql server   common interview questions and answersSql server   common interview questions and answers
Sql server common interview questions and answers
 
Sql server common interview questions and answers page 6
Sql server   common interview questions and answers page 6Sql server   common interview questions and answers page 6
Sql server common interview questions and answers page 6
 
Sql server common interview questions and answers page 5
Sql server   common interview questions and answers page 5Sql server   common interview questions and answers page 5
Sql server common interview questions and answers page 5
 
Sql server common interview questions and answers page 4
Sql server   common interview questions and answers page 4Sql server   common interview questions and answers page 4
Sql server common interview questions and answers page 4
 
Sql server common interview questions and answers page 2
Sql server   common interview questions and answers page 2Sql server   common interview questions and answers page 2
Sql server common interview questions and answers page 2
 
Sql server – 2008 – hardware and software requirements for installing sql se
Sql server – 2008 – hardware and software requirements for installing sql seSql server – 2008 – hardware and software requirements for installing sql se
Sql server – 2008 – hardware and software requirements for installing sql se
 
Speeding up queries with semi joins and anti-joins
Speeding up queries with semi joins and anti-joinsSpeeding up queries with semi joins and anti-joins
Speeding up queries with semi joins and anti-joins
 
Speed up sql
Speed up sqlSpeed up sql
Speed up sql
 
Speed up sql server apps - visual studio magazine
Speed up sql server apps  - visual studio magazineSpeed up sql server apps  - visual studio magazine
Speed up sql server apps - visual studio magazine
 
See sql server graphical execution plans in action tech republic
See sql server graphical execution plans in action   tech republicSee sql server graphical execution plans in action   tech republic
See sql server graphical execution plans in action tech republic
 
Reviewing sql server permissions tech republic
Reviewing sql server permissions   tech republicReviewing sql server permissions   tech republic
Reviewing sql server permissions tech republic
 
Query optimization how to search millions of record in sql table faster -
Query optimization   how to search millions of record in sql table faster  -Query optimization   how to search millions of record in sql table faster  -
Query optimization how to search millions of record in sql table faster -
 
Optimize sql server queries with these advanced tuning techniques tech repu
Optimize sql server queries with these advanced tuning techniques   tech repuOptimize sql server queries with these advanced tuning techniques   tech repu
Optimize sql server queries with these advanced tuning techniques tech repu
 
New date datatypes in sql server 2008 tech republic
New date datatypes in sql server 2008   tech republicNew date datatypes in sql server 2008   tech republic
New date datatypes in sql server 2008 tech republic
 

How do i... query foreign data using sql server's linked servers tech_repu

  • 1. How do I... Query foreign data using SQL Server's linked servers? | TechRepublic ZDNet Asia SmartPlanet TechRepublic Log In Join TechRepublic FAQ Go Pro! Blogs Downloads Newsletters Galleries Q&A Discussions News Research Library IT Management Development IT Support Data Center Networks Security Home / Blogs / The Enterprise Cloud Follow this blog: The Enterprise Cloud How do I... Query foreign data using SQL Server's linked servers? By Susan Harkins July 2, 2007, 12:47 PM PDT This information is also available as a PDF download. If you have a magic wand or a special relationship with some data fairy, all of your data is in the same database on the same server. Most of us aren’t that lucky. Sometimes, the data we need is a non-database format or resides on a different server. SQL Server is flexible enough to offer a number of ways to get the data you need. One of the easiest methods is to directly link to the data via a linked server. (Microsoft SQL Server 2005 Express Edition also supports linked servers.) What’s a linked server? A linked server is simply a connection to an Object Linking and Embedding Database (OLEDB) data source. Technically, OLEDB is a Microsoft standard API for retrieving data from a wide variety of data. If that’s clear as mud, don’t worry. The good news is that it’s flexible enough to link to database and non-database formats, such as a spreadsheet or e-mail client. Simply put, SQL Server supports any OLEDB provider (also called a driver). There’s more good news: You can use Transact-SQL or Management Studio to make the connection. After you create a linked server, SQL Server can log into another database server. That means you can run queries on a remote server. You have two types of linked server queries at your disposal: ad hoc and permanent. Ad hoc links Technically, you won’t use the term linked server to identify an ad hoc query. That term really refers to a SQL Server object. However, you will often see the term used to refer to an ad hoc linked query. An ad hoc query opens and closes the connection. A permanent linked server is always available. Use OPENROWSET for infrequent linked tasks, using the following syntax: OPENROWSET('providername', 'datasource', 'username', 'password', object) An OPENROWSET link consumes less space in your database. Use valid Transact-SQL statements to manipulate the retrieved data. The arguments are self-explanatory, but remember that datasource is the source’s full path, not just a filename. In addition, the provider provides the instructions that SQL Server needs to get in and grab data. They’re specific to the foreign software you’re accessing. Now, let’s look at a simple ad hock query that selects all the records from the Employees table in http://www.techrepublic.com/blog/datacenter/how-do-i-query-foreign-data-using-sql-servers-linked-servers/133[08/29/2012 3:00:28 PM]
  • 2. How do I... Query foreign data using SQL Server's linked servers? | TechRepublic the Microsoft Access sample database, Northwind: SELECT * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0', 'C:Program FilesMicrosoft OfficeOffice11Office11SamplesNorthwind.mdb'; 'admin';'', Employees) AS EmployeesFromAccess Figure A shows the quickly retrieved results, which depend on the user (admin) having the appropriate permissions. (If you want to run this query, be sure to update the path to Northwind.mdb to accommodate your system.) The provider string is specific to the data engine, Jet. The AS keyword provides a name for the new table inside SQL Server. Figure A: Use OPENROWSET for infrequent queries of foreign data (Express edition). If the ad hoc query returns an error, you probably need to enable the ad hoc query feature. (SQL Server disables it by default.) To enable ad hoc queries, run the SQL Server Configuration Manager (the SQL Server Surface Area Configuration utility in the Express edition). Click the Surface Area Configuration For Features link and check the Enable OPENROWSET And OPENDATASOURCE Support option. Then, click OK and close the utility. Alternatively, run the sp_configure stored procedure. Permanent links SQL Server’s linked server object creates a permanent link to a remote server. When the user logs in, SQL Server also logs into the remote server. The first step to retrieving foreign data via a linked server is to let SQL Server know that you plan to talk to another source (server). To do so, execute SQL Server’s sp_addlinkedserver stored procedure, using the following syntax: sp_addlinkedserver server, productname, provider, datasource, location, providerstring, catalog Refer to Table A for an explanation of each of the procedure’s arguments. Notice that a few of the arguments are limited to code. Table A: sp_addlinkedserver stored procedure arguments Parameter Argument Explanation Default Management Studio Constant The local name of the server linked server you’re None Linked Server @server creating The product name of the OLEDB data productname NULL Product Name @srvproduct source you’re adding as a linked server The source’s unique provider NULL Provider Name @provider OLEDB identifier http://www.techrepublic.com/blog/datacenter/how-do-i-query-foreign-data-using-sql-servers-linked-servers/133[08/29/2012 3:00:28 PM]
  • 3. How do I... Query foreign data using SQL Server's linked servers? | TechRepublic The name of the data datasource NULL Data Source @datasrc source The location of the location NULL N/A @location linked source file The OLEDB string providerstring that identifies the NULL N/A @provstr source Catalog used with the catalog NULL N/A @catalog connection The arguments aren’t optional, but you won’t use them all together, which explains the NULL value defaults. The provider determines which arguments you need. When using SQL Server, you need only the first two arguments. Now, let’s suppose you want to create a permanent link to another SQL Server database on the Human Resources server. To do so, you’d use the following statement: EXEC sp_addlinkedserver @server = 'EmployeeStats', @provider = 'SQL Server', @datasrc = 'Human Resources' The linked server’s name, EmployeeStats, is a string that you provide to represent the server. It doesn’t exist until you name and create it. The following syntax statements represent the creation of a linked server to several common data sources: Microsoft Access EXEC sp_addlinkedserver @server = 'NorthwindDemo', @srvproduct = 'Microsoft.Jet.OLEDB.4.0', @provider = 'Microsoft.Jet.OLEDB.4.0', @datasrc = 'C:LinkedNorthwind.mdb' Microsoft Excel EXEC sp_addlinkedserver @server = 'ExcelEmployeeData', @srvproduct = 'Microsoft.Jet.OLEDB.4.0', @provider = 'Microsoft.Jet.OLEDB.4.0', @datasrc = 'C:LinkedEmployees.xls' Oracle EXEC sp_addlinkedserver @server = 'OracleDemo', @srvproduct = 'Oracle', @provider = 'MSDAORA', @datasrc = 'OracleAlias' Oracle is a bit different because you must create an alias that points to the Oracle server rather than specify an actual file (@datasrc). Every situation is different. Your best defense is experience and an informed technical staff. SQL Server throws a monkey wrench into the works because it doesn’t return an error if you use the wrong syntax. Instead, any attempt to use the linked server simply fails, but the failure might not be obvious. My best recommendation is to test a query that you know should return data. If you get nothing, you know the linked server isn’t really connecting and the problem is most likely the arguments you fed sp_addlinkedserver to create the linked server. Using Management Studio Using Management Studio to create a linked server is even easier. Look for the Linked Server folder in the Server Objects or Security folder (depending on which version you’re using). The good news is that Management Studio simplifies the process. You still have to enter the product name, provider, and path to the file. If an option is disabled and you need it, as shown in Figure B, you must turn to sp_addlinkedserver. In this case, Access doesn’t support the Location and http://www.techrepublic.com/blog/datacenter/how-do-i-query-foreign-data-using-sql-servers-linked-servers/133[08/29/2012 3:00:28 PM]
  • 4. How do I... Query foreign data using SQL Server's linked servers? | TechRepublic Catalog options, so Management Studio disables them. Figure B: Management Studio doesn’t support all of the options for every provider (Express edition). Retrieving data Once the linked server exists, you can use it to query data, just as if you were working with SQL Server tables. Figure C shows the result of retrieving all the Employee records from Northwind using the SQL statement via a linked server named NorthwindDemo: SELECT * FROM NorthwindDemo...Employees The statement identifies the remote server and the table from which you’re retrieving data. Figure C: Retrieve Access data via a linked server (Express edition). When querying data via the ExcelData linked server, include a named range as follows: SELECT * FROM ExcelData, Employees http://www.techrepublic.com/blog/datacenter/how-do-i-query-foreign-data-using-sql-servers-linked-servers/133[08/29/2012 3:00:28 PM]
  • 5. How do I... Query foreign data using SQL Server's linked servers? | TechRepublic One or two gotchas The biggest catch to all this simplicity is, as always, security. If you’re working with Windows Authentication, the system accommodates well. If the user has the appropriate permissions for the servers and data sources, linked queries will work. If you have users outside the Windows Authentication environment, you can use a linked login. Create a standard login and assign the appropriate permissions on the remote server. Then, from the sending server, use sp_addlinkedsrvlogin to map local logins to the remote logins using the following syntax: sp_addlinkedsrvlogin remoteservername, useseif, locallogin, remoteuser, remotepassword For instance, after executing the following statement, the user logging in locally as Susan1 with the password rabbitX will have access to data via the NorthwindDemo linked server if you’ve correctly mapped the logins: EXEC sp_addlinkedsrvlogin @rmtsrvname = 'NorthwindDemo', @useseif = FALSE, @locallogin = 'NULL', @rmtuser = 'Susan1', @rmtpassword = 'rabbitX' Table B describes the sp_addlinkedsrvlogin arguments. Table B: sp_addlinkedsrvlogin arguments Argument Explanation Constant server The server’s name @rmtsrvname Use with Windows Integrated Security to useseif @useseif authorize users locallogin Your local login @locallogin remoteuser The user name @rmtuser remotepassword The password @rmtpassword Another catch is the ever-growing, ever-changing list of providers and connection strings that you’ll need. You’ll find a comprehensive list of provider strings at ConnectionStrings.com. Provider names aren’t intuitive either. Table C lists some common provider names. Table C: Provider names SQL Server SQLNCLI Oracle MSDAORA Oracle, version 8 and later OraOLEDB.Oracle Access/Jet and Excel Microsoft.Jet.OLEDB.4.0 ODBC data source MSDASQL IBM DB2 Database DB2OLEDB Susan Sales Harkins is an independent consultant and the author of several articles and books on database technologies. Her most recent book is Mastering Microsoft SQL Server 2005 Express, with Mike Gunderloy, published by Sybex. Other collaborations with Gunderloy are Automating Microsoft Access 2003 with VBA, Upgrader’s Guide to Microsoft Office System 2003, ICDL Exam Cram 2, and Absolute Beginner’s Guide to Microsoft Access 2003, all published by Que. Currently, Susan volunteers as the Publications Director for Database Advisors. You can reach her at ssharkins@setel.com. Get IT Tips, news, and reviews delivered directly to your inbox by subscribing to TechRepublic’s free http://www.techrepublic.com/blog/datacenter/how-do-i-query-foreign-data-using-sql-servers-linked-servers/133[08/29/2012 3:00:28 PM]
  • 6. How do I... Query foreign data using SQL Server's linked servers? | TechRepublic newsletters. Restore your SQL Server Solid state drive storage: database using transaction Good for the enterprise? logs 0 Join the conversation! Add Your Opinion Comments Follow via: Staff Picks Top Rated Most Recent My Contacts See All Comments Log in to display your contacts' posts. Once logged in, adding contacts is simple. Just mouse over any member's photo or click any member's name then click the "Follow" button. You can easily manage your contacts within your account contacts page. See all comments Join the TechRepublic Community and join the conversation! Signing-up is free and quick, Do it now, we want to hear your opinion. Join Login http://www.techrepublic.com/blog/datacenter/how-do-i-query-foreign-data-using-sql-servers-linked-servers/133[08/29/2012 3:00:28 PM]