Related
I have five databases, In that three databases having column Countries and two databases having column Countryrelease..
I am using a cursor, so if I use exists that particular column is throwing an error that column not exists how to handle this one.
Syntax
if exists(select 1 from table where column name='Countries')
select do some operation
else
select do some operation
You want to make use of the meta data within the SQL instance.
This will work for you ...
if (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'YourTableName' AND COLUMN_NAME = 'Countries') = 1
-- The "Countries" column exists
select do some operation
else
select do some operation
I have been tasked with providing a "query" to a teammate who want an easy method of validating that all objects have been deployed to QA or Production PostgreSQL database servers.
Specifically the requester wants to be able to confirm that all tables, functions, sequences, indexes, views, schemas, and triggers exist in each environment and/or which ones are missing from one environment or another when new applications are deployed.
So far I have found queries for identifying indexes and the columns/column order they are in (Position of the column in the index), can query tables in information_schema for other objects, and have learned about tools for generating full diffs of the schemas (How to check difference between two databases in PostgreSQL?). The useful tool apgdiff gives SQL output to synchronize databases, but I did not see how to get a summary of objects that were different and the requester just wants a spreadsheet of what is or isn't there so that missing objects can be deployed. Once all objects are verified to be in existence apgdiff or other tool can be used to further examine that the full table definitions and function & trigger code are identical, but that will be a later task.
My initial attempt for this, without indexes or function parameters is a UNION query to be run separately on each environment, but code to run this against all environments and combine the results is desired, too.
select routine_name as object_name, routine_schema as schema_name, 'routine' as object_type, 'yes' as object_exists from information_schema.routines where routine_schema in ( 'shema1','schema2','schema3' ) union
select schema_name as object_name, schema_name as schema_name, 'schema' as object_type, 'yes' as object_exists from information_schema.schemata where schema_name in ( 'shema1','schema2','schema3' ) union
select sequence_name as object_name, sequence_schema as schema_name, 'sequence' as object_type, 'yes' as object_exists from information_schema.sequences where sequence_schema in ( 'shema1','schema2','schema3' ) union
select table_name as object_name, table_schema as schema_name, 'table' as object_type, 'yes' as object_exists from information_schema.tables where table_schema in ( 'shema1','schema2','schema3' ) union
select trigger_name as object_name, trigger_schema as schema_name, 'trigger' as object_type, 'yes' as object_exists from information_schema.triggers where trigger_schema in ( 'shema1','schema2','schema3' ) union
select table_name as object_name, table_schema as schema_name, 'view' as object_type, 'yes' as object_exists from information_schema.views where table_schema in ( 'shema1','schema2','schema3' )
order by object_type, schema_name, object_name;
After a few revisions this is what I ended up with. It uses the dblink extension (required as a pre-requisite, and in this case installed in a schema named "extension_data") to query three different environments from one session in pgAdmin, psql, etc. The output shows the object name, object type, and which of the three environments have the object loaded. In the cases of indexes I included the table name, type (USING clause) and ordered column list rather than the name since those are the important parts of the index and system generated names could theoretically be different. I also included a column for "object_info" which contains CREATE INDEX commands for indexes that don't exists for easy access and the description of the various pg_settings settings that are also queried.
do $$
-- Two changes are needed below:
-- (1) the schema list needs to be updated
-- (2) the dblink connection information for each environment needs to be updated
-- Execute this in pgadmin while connected to one of the environments. If the username and
-- password are the same in all three environments then they do not need to be listed in
-- the dblink connection strings below
declare
rc bigint := 0;
r RECORD;
-- Necessary change #1: put the schemas you care about here
v_schema_list text := '''schema1'',''schema2'',''schema3'',''schema4''';
-- This is a large query looking at database settings, functions (routines), schemas, sequences, tables, triggers, views, and indexes
-- For functions, the parameter list is important since the same function name can exist with a different number of parameters
-- or the parameters in a different order. This query is not looking at parameter defaults.
-- For indexes, the name of the index isn't important to a functioning system, but the type of index and column order is
-- For tables, this only looks for the existence of the table, not the column order nor constraints, but those could be added later
v_sql text := 'select name||'' = ''||setting as object_name, ''setting'' as object_type, category||'': ''||short_desc as object_info
from pg_settings
union
select routine_schema||''.''||routine_name||''(''||coalesce(string_agg(parameters.parameter_name||'' ''||parameters.data_type,'', ''),'''')||'')'' as object_name
, ''routine'' as object_type
, ''''::text as object_info
from information_schema.routines
left join lateral
(select parameter_name, parameters.data_type, parameters.ordinal_position
from information_schema.parameters
where parameters.specific_schema = routines.specific_schema
and parameters.specific_name = routines.specific_name
order by ordinal_position) parameters
on true
where routine_schema in ('||v_schema_list||')
group by routine_name, routine_schema
union
select schema_name||''.''||schema_name as object_name, ''schema'' as object_type, ''''::text as object_info
from information_schema.schemata where schema_name in ('||v_schema_list||')
union
select sequence_schema||''.''||sequence_name as object_name, ''sequence'' as object_type, ''''::text as object_info
from information_schema.sequences where sequence_schema in ('||v_schema_list||')
union
select table_schema||''.''||table_name as object_name, ''table'' as object_type, ''''::text as object_info
from information_schema.tables where table_schema in ('||v_schema_list||')
union
select trigger_schema||''.''||trigger_name as object_name, ''trigger'' as object_type, ''''::text as object_info
from information_schema.triggers where trigger_schema in ('||v_schema_list||')
union
select table_schema||''.''||table_name as object_name, ''view'' as object_type, ''''::text as object_info
from information_schema.views where table_schema in ('||v_schema_list||')
union
select substring(indexdef,3+position(''ON'' in indexdef)) as object_name, ''index'' as object_type, indexdef as object_info
from pg_indexes where schemaname in ('||v_schema_list||')
order by object_type, object_name; ';
begin
drop table if exists object_list;
drop table if exists object_comparison;
create temp table object_list (object_name text, object_type text, object_info text, environment text);
for r in
-- Necessary change #2: update connection information for each database here
select 'prod' as conn, 'dbname=your_prod_db_name port=5432 host=your_prod_server username=your_prod_user password=your_prod_password' as conn_string union
select 'qa' as conn, 'dbname=your_qa_db_name port=5432 host=your_qa_server username=your_qa_user password=your_qa_password' as conn_string union
select 'dev' as conn, 'dbname=your_dev_db_name port=5432 host=your_dev_server username=your_dev_user password=your_dev_password' as conn_string
loop
begin
perform extension_data.dblink_disconnect(r.conn);
exception when others then
null;
end;
perform extension_data.dblink_connect(r.conn, r.conn_string);
perform extension_data.dblink_open(r.conn, 'object_list',v_sql);
GET CURRENT DIAGNOSTICS rc := ROW_COUNT;
while rc > 0 loop
insert into object_list
SELECT *, r.conn as environment
FROM extension_data.dblink_fetch(r.conn, 'object_list', 500) AS (object_name text, object_type text, object_info text);
GET CURRENT DIAGNOSTICS rc := ROW_COUNT;
end loop;
perform extension_data.dblink_close(r.conn, 'object_list');
perform extension_data.dblink_disconnect(r.conn);
end loop;
create temp table object_comparison as (
select coalesce(dev.object_name,coalesce(qa.object_name,prod.object_name)) as object_name
, coalesce(dev.object_type,coalesce(qa.object_type,prod.object_type)) as object_type
, dev.environment as dev
, qa.environment as qa
, prod.environment as prod
, coalesce(prod.object_info,coalesce(qa.object_info,dev.object_info)) as object_info
from (select * from object_list where environment = 'dev') dev
full outer join (select * from object_list where environment = 'qa') qa
on dev.object_name = qa.object_name
and dev.object_type = qa.object_type
full outer join (select * from object_list where environment = 'prod') prod
on coalesce(dev.object_name,qa.object_name) = prod.object_name
and coalesce(dev.object_type,qa.object_type) = prod.object_type
);
end;
$$ language plpgsql;
select * from object_comparison where dev is null or qa is null or prod is null;
How do I retrieve all record from every table (Ex: table1, table2, table3, ... tableN ) where id = 1 from single database (EX: database1) in SQL Server 2008 R2?
Let's suppose I have 1 database and in that I have infinite tables (EX. table1,table2, ....,tableN). Is this possible to get all the record from entire database where id=1 on each table? I think it is possible with SQL information_schema.table or information_schema.column, but I don't know how to use this.
Any help appreciated
Thanks in advance!
You can use the undocumented sp_msforeachtable
sp_msforeachtable
#command1 = 'SELECT * FROM ? WHERE id=1',
#whereand = ' And Object_id In (Select Object_id From sys.columns Where name=''id'')'
#command1 is your query. The question mark is a placeholder the stored procedure uses to insert the table name.
#whereand limits the search to just tables that have the column named id
I don't have much idea of MySQL, Use this in db2
Select C.NAME,C.ROLLNUMBER from TABLE1 C,TABLE2 A where C.ROLLNUMBER=A.ROLLNUMBER and id = 1 order by C.CIRCLENAME
hope this will work too..
If you want to mention the tables manually try this.
SELECT COL1,COL2,COL3....COLN FROM TABLE1 WHERE ID=1
UNION ALL
SELECT COL1,COL2,COL3....COLN FROM TABLE2 WHERE ID=1
UNION ALL
SELECT COL1,COL2,COL3....COLN FROM TABLE2 WHERE ID=1
:
:
:
UNION ALL
SELECT COL1,COL2,COL3....COLN FROM TABLEN WHERE ID=1
Note: The col1,col2,col3...coln Should Be Same Datatype in All The Mentioned Tables
This for dynamic building of all the tables with id =1
SELECT STUFF((SELECT '
UNION ALL
SELECT COL1,COL2,COL3..COLN FROM '+TABLE_NAME + ' WHERE ID=1 '
FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE' FOR XML PATH(''),type).value('.', 'NVARCHAR(MAX)'),1,11,'')
Note:Your tables must contain the common column i.e ID .change the column names as per you need but all the mentioned columns in select statement should be contain in all of your tables.
The best possible way would be to generate a dynamic query and executed it to get the required information.
To generate the query you can use the schema information related system tables and feed the data in a fixed format table. i.e. make a fix format tables having a defined column structure. That will help to feed the data.
For example:
CREATE TABLE AllTableData
(
TableId int,
TableName nvarchar(250),
TableData NVARCHAR(max),
SelectedId int
)
Where TableId is the id of table from system table and TableData will contain the concatenated value string of all columns of a table with some separator identifier.
;WITH T AS
(
SELECT
T1.*
FROM
INFORMATION_SCHEMA.TABLES T1
INNER JOIN INFORMATION_SCHEMA.COLUMNS T2 ON T2.TABLE_NAME = T2.TABLE_NAME
WHERE
T2.COLUMN_NAME = 'Id'
AND T1.TABLE_TYPE='BASE TABLE'
),
DynamicQuery AS (
SELECT
1 AS Id,
CONCAT(
'SELECT ', QUOTENAME(T.TABLE_NAME,''''),' AS [TableName],',
CONCAT(' CONCAT(',STUFF((SELECT CONCAT(', [' , C.COLUMN_NAME,']' )
FROM INFORMATION_SCHEMA.COLUMNS C
WHERE C.TABLE_NAME = T.TABLE_NAME
FOR XML PATH('')), 1, 1, ''),') AS [TableData]'
)
,', 1 AS [SelectedId] FROM ', T.TABLE_NAME,' WHERE Id = 1'
) [FinalString]
FROM T
)
SELECT DISTINCT
STUFF((SELECT ' UNION ALL ' + DQ2.FinalString
FROM DynamicQuery DQ2
WHERE DQ2.Id = DQ1.Id
FOR XML PATH('')), 1, 10, '') [FinalString]
FROM DynamicQuery DQ1
GROUP BY DQ1.Id, DQ1.FinalString
I think, this is what you are searching for.
In sql server 2012 i'm using
USE myDatabase;
GO
SELECT *
FROM sys.objects
WHERE type = 'U';
Is it possible to do the same in syBase ?
In order to get a list of all tables in the current database, you can filter the sysobjects table by type = āUā e.g.:
select convert(varchar(30),o.name) AS table_name
from sysobjects o
where type = 'U'
order by table_name
Further Reference
Here is an example of getting all table names in MSSQL or SQL Server database:
USE test; //SELECT DATABASE
SELECT table_name FROM information_schema.tables WHERE table_type = 'base table'
or you can use sys.tables to get all table names from selected database as shown in following SQL query
USE test; //SELECT DATABASE
SELECT * FROM sys.tables
That's all on how to find all table names from database in SQL Server.
For SQL Anywhere 16, this query works fine.
select * from sys.SYSTABLE
It gives a list of the table_names along with the information like table id, table page count, etc.
In order to list all the tables and rows count, the following query can be used.
select convert(varchar(30),o.name) AS table_name,
row_count(db_id(), o.id) AS row_count
from sysobjects o
where type = 'U'
order by table_name
In order get a list of tables which has the table name like, use the following query.
Here table_name has to be replaced with your desired name.
select convert(varchar(30),o.name) AS table_name,
row_count(db_id(), o.id) AS row_count
from sysobjects o
where type = 'U' and o.name like '%table_name%'
order by table_name
I need a query in sql to get total columns in a table.Can anybody help?
SELECT COUNT(COLUMN_NAME)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_CATALOG = 'database' AND TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'table'
This query gets the columns name
SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.Columns where TABLE_NAME = 'YourTableName'
And this one gets the count
SELECT Count(*) FROM INFORMATION_SCHEMA.Columns where TABLE_NAME = 'YourTableName'
In MS-SQL Server 7+:
SELECT count(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'mytable'
The below query will display all the tables and corresponding column count in a database schema
SELECT Table_Name, count(*) as [No.of Columns]
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_schema = 'dbo' -- schema name
group by table_name
Select Table_Name, Count(*) As ColumnCount
From Information_Schema.Columns
Group By Table_Name
Order By Table_Name
This code show a list of tables with a number of columns present in that table for a database.
If you want to know the number of column for a particular table in a database
then simply use where clause e.g. where Table_Name='name_your_table'
You can try below query:
select
count(*)
from
all_tab_columns
where
table_name = 'your_table'
It can be done using:-
SELECT COUNT(COLUMN_NAME) 'NO OF COLUMN' FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Address'
Correction to top query above, to allow to run from any database
SELECT COUNT(COLUMN_NAME) FROM [*database*].INFORMATION_SCHEMA.COLUMNS WHERE
TABLE_CATALOG = 'database' AND TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'table'
In my situation, I was comparing table schema column count for 2 identical tables in 2 databases; one is the main database and the other is the archival database. I did this (SQL 2012+):
DECLARE #colCount1 INT;
DECLARE #colCount2 INT;
SELECT #colCount1 = COUNT(COLUMN_NAME) FROM MainDB.INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'SomeTable';
SELECT #colCount2 = COUNT(COLUMN_NAME) FROM ArchiveDB.INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'SomeTable';
IF (#colCount1 != #colCount2) THROW 5000, 'Number of columns in both tables are not equal. The archive schema may need to be updated.', 16;
The important thing to notice here is qualifying the database name before INFORMATION_SCHEMA (which is a schema, like dbo). This will allow the code to break, in case columns were added to the main database and not to the archival database, in which if the procedure were allowed to run, data loss would almost certainly occur.
To get the list of all columns of the SQL table
select column_name from information_schema.columns where table_name=[dbo].[your_table_name]
To get the list of number of columns of the SQL table
select count(column_name) from information_schema.columns where table_name=[dbo].[your_table_name]
To get the total number of columns in table.
SELECT COUNT(COLUMN_NAME) FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'database_name' AND TABLE_NAME = 'table_name';