Find the database in which a table exists in the current database server

Source: Internet
Author: User

1 --2 --find the database in which a table exists in the current database server, and the sqlserver2008 test passes3 --4 Declare @tableName varchar( -)5 --This sets the name of the table to be queried6 Set @tableName=' Products'7  8 --Clean up temporary tables9 if object_id('tempdb: #tmpdbs') is  not NULL BeginTen     Drop Table#tmpdbs One End A if object_id('tempdb: # #tmpResults') is  not NULL Begin -     Drop Table# #tmpResults - End the   - --Create a global temporary table manually, insert only using INSERT INTO, and cannot use select INTO, which automatically creates temporary tables - Create Table# #tmpResults ( -DbNamevarchar( -), +Namevarchar( -), -XTypevarchar( -) + ) A   at SelectName,row_number () Over(Order  byName) asrowID into#tmpdbs fromMaster.. sysdatabases Name - Declare @dbName varchar( -) - Declare @rowid int - Declare @count int -   - Set @rowid=1 in Select @count=Count(*) from#tmpdbs -   to  while @rowid <= @count + begin -     --print (@rowid) the     Select @dbName=[Name]  from#tmpdbswhererowID=@rowid *     exec('INSERT INTO # #tmpResults Select" "+@dbName+" "As Dbname,name,xtype from'+@dbName+'.. SysObjects Where (xtype="'U"'or xtype="'SN"') and Name=" "+@tableName+" "ORDER by Name') $     Set @rowid=@rowid+1Panax Notoginseng End -   the --View Results + Select *  from# #tmpResults A   the --Clean up temporary tables + if object_id('tempdb: #tmpdbs') is  not NULL Begin -     Drop Table#tmpdbs $ End $ if object_id('tempdb: # #tmpResults') is  not NULL Begin -     Drop Table# #tmpResults - End

Find the database in which a table exists in the current database server

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.