No of records in each table [duplicate] - sql

This question already has answers here:
Query to list number of records in each table in a database
(23 answers)
Closed 5 years ago.
How to get a list of all tables with no of records in a particular database in SQL Server.
Thanks

Here's another option - not dependent on INFORMATION_SCHEMA.
This would also allow you to alter your where clause (you may edit your #QUERY accordingly).
DECLARE #QUERY VARCHAR(MAX)
SET #QUERY = ''
/*
* Create a long query with a row count + table name.
* You may alter your where clause here
*/
SELECT #QUERY =
#QUERY + ' SELECT COUNT(*), ''' + QUOTENAME(name)
+ ''' FROM ' + QUOTENAME(name) + CHAR(13)
+ 'UNION ALL'
FROM sys.tables
--Get rid of the last 'UNION ALL'...
SELECT #QUERY = LEFT(#QUERY, LEN(#QUERY) - 10)
--Prepare a temp table - drop if exists and then create it
IF object_id('tempdb..#TableResults') IS NOT NULL
DROP TABLE #TableResults
CREATE TABLE #TableResults(
Count INT,
TableName VARCHAR(MAX)
);
--Insert the main query result into the temp table
INSERT INTO #TableResults
EXEC(#QUERY);
--Select all from the temp table
SELECT * FROM #TableResults
WHERE COUNT = 0

You will need to use Dynamic SQL and check for existance of rows in each table
declare #sql nvarchar(max)
select #sql = isnull(#sql + ' union all ' + char(13) , convert(nvarchar(max), ''))
+ 'select tbl_name = ''' + name + ''' '
+ 'where not exists (select * from ' + quotename(name) + ')'
from sys.tables
print #sql
exec (#sql)

Did you mean this
SELECT COUNT(*) FROM
INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME IN
(
SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE')
Saravanan

Related

Is there any way to create View or temp table from dynamic SQL query

I have a query that provides some data I want to save this data in a temp table or view. Please help
The query is given below:
IF OBJECT_ID('tempdb..#NLSPMTS3_tmp') IS NOT NULL
DROP TABLE #NLSPMTS3_tmp
SELECT *
INTO #NLSPMTS3_tmp
FROM vwNLSPayments4
DECLARE #Columns AS VARCHAR(MAX)
SELECT #Columns = COALESCE(#Columns + ', ','') + QUOTENAME(b.mop_fpd)
FROM (SELECT DISTINCT mop_fpd FROM #NLSPMTS3_tmp) AS B
ORDER BY B.mop_fpd
-- You can't remove nulls from a PIVOT, so you have to create a second set of column names
DECLARE #NullColumns as VARCHAR(MAX)
SELECT #NullColumns =
COALESCE(#NullColumns + ', ','') + 'ISNULL(' + QUOTENAME(b.mop_fpd) + ', 0) ' + QUOTENAME(b.mop_fpd)
FROM (Select DISTINCT mop_fpd FROM #NLSPMTS3_tmp) AS B
ORDER BY B.mop_fpd
DECLARE #SQL as NVARCHAR(MAX)
SET #SQL = 'SELECT acctrefno, ' + #NullColumns + '
FROM
(SELECT payment_amount, acctrefno, mop_fpd
FROM
nlsdev.dbo.vwnlsPayments2
) as PivotData
PIVOT
(sum(payment_amount) FOR mop_fpd IN (' + #Columns + ')) AS PivotResult ORDER BY acctrefno'
EXEC (#SQL)
I just simply put create a view as <above SQL query> but it did not work.

Resultset from Facts across different schemas

We have a DB which has several schemas and each schema has a Fact table. I need to prepare a result set with schema name, max(MTH_DT) from Fact and distinct MTH_DT counts from each Fact table.
SCHEMA_NAME MAX(MTH_DT) DISTINCT_COUNT(MTH_DT)
SCHM_1 11/30/2015 24
SCHM_2 10/31/2015 24
SCHM_3 11/30/2015 36
SCHM_4 10/31/2015 24
SCHM_5 11/30/2015 24
How can I get the resultset in this fashion?
Here it goes
Just uncomment the EXECUTE statement when you are sure of the query and run the query:
DECLARE #SQL VARCHAR(MAX) = ''
SELECT #SQL += 'SELECT '''+T.TABLE_NAME+''' AS [SCHEMA_NAME],MAX(MTH_DT) AS [MAX(MTH_DT)] ,COUNT(MTH_DT) AS [DISTINCT_COUNT(MTH_DT)] FROM '+T.TABLE_SCHEMA+'.'+T.TABLE_NAME + ' UNION ' FROM INFORMATION_SCHEMA.TABLES AS T WHERE T.TABLE_NAME like 'SCHM_%'
SELECT #SQL = SUBSTRING(#SQL,1,LEN(#SQL) - LEN('UNION'))
PRINT (#SQL)
--EXECUTE (#SQL)
Here is a safer way to build your dynamic sql than using INFORMATION_SCHEMA.TABLES. I left off the group by because it is a constant so you don't actually need a group by.
declare #SQL nvarchar(MAX) = ''
select #SQL = #SQL + 'select ''' + name + ''' as SchemaName, MAX(MTH_DT) as MaxMTH_DT, COUNT(distinct MTH_DT) as DISTINCT_COUNT_MTH_DT from ' + name + '.Fact union all '
from sys.schemas
where SCHEMA_ID > 4
and SCHEMA_ID < 16384
Select #SQL = LEFT(#SQL, LEN(#SQL) - 9) + ' order by SchemaName'
select #SQL

Counting rows in the table which have 1 or more missing values

Could you please advise how to find the number of rows in the table which have 1 or more missing values? The missing values are represented in my table by question marks = '?'. The table has 15 columns and ~50k rows. When I run the following query for some of the columns I can receive some results:
SELECT
COUNT(*)
FROM table_name
WHERE column_name ='?'
However I have also columns which bring me result: "Error converting data type varchar to float"
I would like to be able to find the number of rows in the table which have 1 or more missing values using 1 query/not run separately for each column.
Thank you in advance for your support!
Select Count(*)
From mySchema.myTable
Where Cast(Col1 As NVarChar(128)) +
Cast(Col2 As NVarChar(128)) +
Cast(Coln As NVarChar(128)) Like '%?%'
It's ugly and WILL be slow and you may need to modify the Casts accordingly, but should do the trick.
This should work for any column:
select count(*)
from table_name
where column_name is null or cast(column_name as varchar(255)) = '?';
Try following query:
Just set table name and it will get all columns
Also you can give value_to_match like '?' in your case or any other if you want.
DECLARE #table_name nvarchar(max) = 'table_name'
DECLARE #value_to_match nvarchar(max) = '1'
DECLARE #query nvarchar(max) = ''
DECLARE #Condition nvarchar(max) = ' OR ' -- 1 OR when you want to count row if any column has that value -- 2 when you want all all columns to have same value
SELECT #query = #query + ' cast(' + COLUMN_NAME + ' as nvarchar(500)) = ''' + #value_to_match + '''' + #Condition FROM informatioN_schema.columns WHERE table_name = #table_name
if ##rowcount = 0
BEGIN
SELECT 'Table doesn''t Exists'
RETURN
END
SELECT #query = LEFT(#query,LEN(#query)-3)
PRINT ('select count(9) FROM ' + #table_name + ' WHERE ' + #query)
EXEC ('select count(9) FROM ' + #table_name + ' WHERE ' + #query)

Moving table from one database to another with primary key and other keys

I want to move all the table from one database to another with primary key and all other keys
using SQL queries. I am using SQL Server 2005 and I got a SQL queries to move the table but the keys are not moved.
And my queries is as follows
set #cSQL='Select Name from SRCDB.sys.tables where Type=''U'''
Insert into #TempTable
exec (#cSQL)
while((select count(tName) from #t1Table)>0)
begin
select top 1 #cName=tName from #t1Table
set #cSQL='Select * into NEWDB.dbo.'+#cName+' from SRCDB.dbo.'+#cName +' where 1=2'
exec(#cSQL)
delete from #t1Table where tName=#cName
end
where SRCDB is the name of source database and NEWDB is the name of destination database
How can I achieve this..?
Can anyone help me in this...
Thank you...
The following T-SQL statement move all the table, primary key and foreign key from one database to another. Notice that the method SELECT * INTO FROM ... WHERE 1 = 2 does not create COMPUTED columns and user-data types. Suppose also that all primary keys are clustered
--ROLLBACK
SET XACT_ABORT ON
BEGIN TRAN
DECLARE #dsql nvarchar(max) = N''
SELECT #dsql += ' SELECT * INTO NEWDB.dbo.' + name + ' FROM SRCDB.dbo. ' + name + ' WHERE 1 = 2'
FROM sys.tables
--PRINT #dsql
EXEC sp_executesql #dsql
SET #dsql = N''
;WITH cte AS
(SELECT 1 AS orderForExec, table_name, column_name, constraint_name, ordinal_position,
'PRIMARY KEY' AS defConst, NULL AS refTable, NULL AS refCol
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE OBJECTPROPERTY(OBJECT_ID(constraint_name), 'IsPrimaryKey') = 1
UNION ALL
SELECT 2, t3.table_name, t3.column_name, t1.constraint_name, t3.ordinal_position,
'FOREIGN KEY', t2.table_name, t2.column_name
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS as t1
JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE t2 ON t1 .UNIQUE_CONSTRAINT_NAME = t2.CONSTRAINT_NAME
JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE t3 ON t1.CONSTRAINT_NAME = t3.CONSTRAINT_NAME
AND t3.ordinal_position = t2.ordinal_position
)
SELECT #dsql += ' ALTER TABLE NEWDB.dbo.' + c1.table_name +
' ADD CONSTRAINT ' + c1.constraint_name + ' ' + c1.defConst + ' (' +
STUFF((SELECT ',' + c2.column_name
FROM cte c2
WHERE c2.constraint_name = c1.constraint_name
ORDER BY c2.ordinal_position ASC
FOR XML PATH(''), TYPE
).value('.', 'nvarchar(max)'), 1, 1, '') + ')' +
CASE WHEN defConst = 'FOREIGN KEY' THEN ' REFERENCES ' + c1.refTable + ' (' +
STUFF((SELECT ',' + c2.refCol
FROM cte c2
WHERE c2.constraint_name = c1.constraint_name
ORDER BY c2.ordinal_position ASC
FOR XML PATH(''), TYPE
).value('.', 'nvarchar(max)'), 1, 1, '') + ')' ELSE '' END
FROM (SELECT DISTINCT orderForExec, table_name, defConst, constraint_name, refTable FROM cte) AS c1
ORDER BY orderForExec
--PRINT #dsql
EXEC sp_executesql #dsql
COMMIT TRAN
You can generate customized script of Source Database and run the script for Destination Database.
Here is the link and slightly better [one][2]
Get the complete table and then perform the delete queries on Destination database as per requirement
If you want to do with Query. I guess this link would be helpful
DECLARE #strSQL NVARCHAR(MAX)
DECLARE #Name VARCHAR(50)
SELECT Name into #TempTable FROM SRCDB.sys.tables WHERE Type='U'
WHILE((SELECT COUNT(Name) FROM #TempTable) > 0)
BEGIN
SELECT TOP 1 #Name = Name FROM #TempTable
SET #strSQL = 'SELECT * INTO NEWDB.dbo.[' + #Name + '] FROM SRCDB.dbo.[' + #Name + ']'
EXEC(#strSQL)
DELETE FROM #TempTable WHERE Name = #Name
END
DROP TABLE #TempTable
If you have destination table already created then just set identity insert on and change query like below :
SET #strSQL = ' SET IDENTITY_INSERT NEWDB.dbo.[' + #Name + '] ON; ' +
' INSERT INTO NEWDB.dbo.[' + #Name + '] SELECT * FROM SRCDB.dbo.[' + #Name + ']' +
' SET IDENTITY_INSERT NEWDB.dbo.[' + #Name + '] OFF '
UPDATE :
If you don't want records and only want to create table with all key constaints then check this solution :
In SQL Server, how do I generate a CREATE TABLE statement for a given table?
The following script copies many tables from a source DB into another destination DB, taking into account that some of these tables have auto-increment columns:
http://sqlhint.com/sqlserver/copy-tables-auto-increment-into-separate-database

SQL Select tables / list tables

I would like to ask for help.
As I have 500 plus tables, and I need to search those table's column having some similar words. Is it possible to search and list those tables?
E.g
Table 1 - Name, age, height
Table 2 - Result, Name, Score
Table 3 - Name, Pic, Parent1, Parent2
I wan to do a query to select all the table that any of the column contain the word "%Name%", is this possible?
Just run following query in your db and replace your search string with string and it will work.
SQL for find particular word/value from all columns and tables in a database
DECLARE #SQL VARCHAR(MAX)
DECLARE #valueToFind VARCHAR(1000)
DECLARE #columnName VARCHAR(1000)
SET #valueToFind = 'string'
SET #columnName = '%%'
CREATE TABLE #TMP
(Clmn VARCHAR(500),
CNT INT)
SELECT #SQL=COALESCE(#SQL,'')+CAST('INSERT INTO #TMP Select ''' + TABLE_SCHEMA + '.' + TABLE_NAME + '.' + COLUMN_NAME + ''' AS Clmn, count(*) CNT FROM '
+ TABLE_SCHEMA + '.[' + TABLE_NAME +
'] WHERE [' + COLUMN_NAME + '] LIKE ''%' + #valueToFind + '%'' ;' AS VARCHAR(8000))
FROM INFORMATION_SCHEMA.COLUMNS
JOIN sysobjects B
ON INFORMATION_SCHEMA.COLUMNS.TABLE_NAME = B.NAME
WHERE COLUMN_NAME LIKE #columnName AND xtype = 'U'
AND DATA_TYPE IN ('char','nchar','ntext','nvarchar','text','varchar')
--PRINT (#SQL)
EXEC(#SQL)
SELECT * FROM #TMP WHERE CNT > 0
DROP TABLE #TMP
-----------------------------------------------------------------------------------------