Category Archives: Software

Find the database when table name is known

Requirement:

We have a table name or at least a part of it with us.  We want to know the database to which it belongs. Manually searching is not possible/ difficult as there are many databases having many more tables.

Solution:

We will create a stored procedure which accepts table name as a parameter. The procedure searches for the table name parameter across all user-defined databases in the server. If there is/are any match/matches the program will print out the server name. If there is no match, program prints the same.

Source code:

SET ANSI_NULLS ON
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Satyanarayana Kondapalli
-- Description: find the database in which the required table is present
-- =============================================
CREATE PROCEDURE getDBNameByTable @tblname VARCHAR(80)=NULL
AS
BEGIN
SET NOCOUNT ON;
--check if a parameter is passed as table name
IF (@tblname IS NULL)
BEGIN
PRINT 'Please pass a table name as parameter'
GOTO Error
END
IF OBJECT_ID('tempdb.dbo.#dbnames', 'U') IS NOT NULL
DROP TABLE #dbnames
IF OBJECT_ID('tempdb.dbo.#searchtable', 'U') IS NOT NULL
DROP TABLE #searchtable
CREATE TABLE #searchtable (table_name VARCHAR(80))
DECLARE @name VARCHAR(80)
DECLARE @searchquery VARCHAR(max)
DECLARE @count int
-- create a temp table with all database list
SELECT name INTO #dbnames from sys.databases where name not in ('model','msdb','master','tempdb')
DECLARE findmydb CURSOR FOR
SELECT name from #dbnames
OPEN findmydb
FETCH NEXT FROM findmydb INTO @name
SET @count=0
WHILE @@FETCH_STATUS = 0
BEGIN
--iterate every db to get tables list from each db
SELECT @searchquery='SELECT TABLE_NAME FROM '+@name+'.'+'information_schema.TABLES'
INSERT INTO #searchtable exec (@searchquery)
--if the table is found, print the db name
IF exists(SELECT table_name from #searchtable where table_name like '%'+@tblname+ '%')
BEGIN
SET @count=@count+1
PRINT @name
END
--truncate the table after each iteration
TRUNCATE TABLE #searchtable
FETCH NEXT FROM findmydb INTO @name
END
IF(@count=0)
--if table is not found at all
PRINT 'table does not exist in the server!'
CLOSE findmydb
DEALLOCATE findmydb
Error:return -1
END
GO

Sample:
EXEC getDBNameByTable 'TABLE_NAME'

Not so common SQL concepts

Below are some not so common concepts in SQL server.

  1. Having clause

When we are dealing with aggregate functions like Sum(), count() etc., we generally face difficulty in using them in a WHERE clause.

For example, let us say we have a Customers table which has three columns CustomerID, CustomerName and Product. Because a single customer can buy multiple products, we can insert multiple records for each product a customer buys.

CustomerID CustomerName Product
101 John Bread
102 Smith Milk
101 John Butter

 

Let’s say we want to find the number of customers who purchased at least five products.

The below query will throw an error:

SELECT Customername, count(CustomerName) FROM Customers where count(CustomerName)>=5

Error Message: An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or a select list, and the column being aggregated is an outer reference.

We correct this issue using the below query which uses the having clause:

SELECT Customername, count(CustomerName) FROM cUSTOMERs GROUP BY CustomerName having count(CustomerName)>=5

Note: GROUP BY clause is a must when using having clause.

  1. Exists condition

Syntax: SELECT column_name(s)

FROM table_name

WHERE EXISTS

(SELECT column_name FROM table_name WHERE condition)

The above query first checks if the select query inside the exists condition has data. If yes, it will return the values in the actual query.