I know how to find which table has that column name, by running:
select * From INFORMATION_SCHEMA.COLUMNS Where column_name = 'column value'
What i need now, is to find which tables have that certain column data.
It doesn't matter which column it belongs, I can find it, i just don't know which table to look at.
Joining these tables is not a solution, since there are a lot of tables.
Pls. let me know if you have ideas.
Thanks.
Will this do the job for you?
declare #data varchar(50)
,#sql varchar(max)
select #data = '%test%'
create table #Temp ([Table] varchar(200), [Column] varchar(200), [Data] varchar(max))
select #sql = isnull(#sql, '') + 'insert into #Temp select ''' + sys.tables.name + ''', ''' + sys.columns.name + ''', ' + sys.columns.name + ' from [' + sys.tables.name + '] where [' + sys.columns.name + '] like ''' + #data + ''';'
from sys.tables
inner join sys.columns
on sys.columns.object_id = sys.tables.object_id
exec(#sql)
select * from #Temp order by [Table], [Column]
drop table #Temp
Related
I am working on an example to write dynamic sql to pivot the data in ssis expression builder.It fails to evaluate the expression. Below is the dynamic query:
DECLARE #Cols as NVARCHAR(MAX)
DECLARE #SQL as NVARCHAR(MAX)
SELECT #Cols = COALESCE(#Cols + ', ','') + QUOTENAME(Name)
FROM
(
SELECT DISTINCT Category
FROM Product
) As t1
SET #SQL = 'SELECT *
FROM
(
SELECT ProductID,
Category,
Quantity
FROM Product
) as PivotData
PIVOT
(
COUNT(Quantity)
FOR Category IN (" + #Cols + ")
) AS PivotResult'
I think your double quotes around + #Cols needs to be single quotes, see below.
DECLARE #Cols as NVARCHAR(MAX)
DECLARE #SQL as NVARCHAR(MAX)
SELECT #Cols = COALESCE(#Cols + ', ','') + QUOTENAME(Name)
FROM
(
SELECT DISTINCT Category
FROM Product
) As t1
SET #SQL = 'SELECT *
FROM
(
SELECT ProductID,
Category,
Quantity
FROM Product
) as PivotData
PIVOT
(
COUNT(Quantity)
FOR Category IN (' + #Cols + ')
) AS PivotResult'
I have a table called tbl_site with 50 columns. I want to write some SQL code that will count the number of distinct values and the number of null values for each column without having to run a statement for each column.
I understand this would possibly include running a nested query to information_schema.columns but I am unsure on how to construct the query further. Also null values would include values that are '' and ' ' if possible.
The desired output would be the following:
Column | Distinct | Null
site_id | 100 | 0
sitearea_id | 12 | 0
site_area | 54 | 5
etc....
Try a mixture of count distinct and sum case:
SELECT Column, count(distinct Column) as 'Distinct'
,sum(case when Column is null then 1 else 0 end) as 'Null'
FROM tbl_site
GROUP BY 1
Yeah, I noticed it's MySQL after i made a script for SQL Server ... but anyway here is the code in case someone needs it ... or if you get idea from it how to do it
declare #position int = 1,
#sql nvarchar(max),
#columnCnt int,
#currentColumn nvarchar(50),
#TableName nvarchar(50) = 'YourTableName',
#DBName nvarchar(50) = 'YourDbName';
if (OBJECT_ID('tempdb..#MyRowCount')) IS NOT NULL DROP TABLE #MyRowCount
CREATE TABLE #MyRowCount (ColumnName nvarchar(50), DistinctCount int, NullCount int)
set #columnCnt = (select MAX(ORDINAL_POSITION) from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME = #TableName and TABLE_CATALOG = #DBName)
WHILE (#position <= #columnCnt)
BEGIN
set #currentColumn = (select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME = #TableName and
TABLE_CATALOG = #DBName and
ORDINAL_POSITION = #position)
set #sql = 'INSERT INTO #MyRowCount (ColumnName, DistinctCount, NullCount)
SELECT ''' + #currentColumn + ''',
(SELECT COUNT(DISTINCT [' + #currentColumn + ']) FROM ' + #TableName + ' where [' + #currentColumn + '] IS NOT NULL),
(SELECT COUNT(*) FROM ' + #TableName + ' where [' + #currentColumn + '] IS NULL)';
-- print #sql;
execute (#sql);
set #position = #position + 1;
END
SELECT * FROM #MyRowCount
In MySQL, you can construct the query using:
set #sql = '
select ''[column]'' as col, count(distinct "[column]"), sum("[column]" is null)
from [table] t
';
select group_concat(replace(replace(#sql, '[table]', table_name), '[column]', column_name) separator ' union all ')
from information_schema.columns
where table_name = ?;
The caveat to this approach is that you need to be sure that your group_concat maximum length value is long enough (the default of 1024 won't get you very far).
Then, you can either copy the query to use prepare/execute to run it.
Relatively straight forward question but I am a novice with SQL queries. I'm trying to find in all the tables any record that contains a certain value.
So in a nutshell I want to find in the entire database any instance where the hContactId is 200.
I've tried the following:
USE dbname
SELECT *
FROM sys.Tables
WHERE hContacts.hContactId = 200;
I end up with
You have an error in your SQL syntax; check the manual that
corresponds to your MariaDB server version
I've seen some really complex queries like below that didn't work but surely there should be a way to query all tables for an integer right?
Another thing I tried to the same error message:
declare #sql varchar(8000), #tbl varchar(255), #col varchar(255),
#data varchar(50)
set #data = '200'
declare cur_tbl cursor for
select a.name, b.name from sysobjects a, syscolumns b, systypes c where a.id = b.id and a.type = 'U' and c.xtype = b.xtype and c.name in ( 'int' )
open cur_tbl
fetch next from cur_tbl into #tbl, #col
while ##fetch_status = 0
begin
set #sql = '
if exists (select * from [' + #tbl + '] where convert( varchar(255), [' + #col + '] ) = ''' + #data + ''')
select tbl=''' + #tbl + ''', col=''' + #col + ''', [' + #col + '], * from [' + #tbl + '] where convert( varchar(255), [' + #col + '] ) = ''' + #data + '''
'
exec(#sql)
fetch next from cur_tbl into #tbl, #col
end
close cur_tbl
deallocate cur_tbl
Again just looking for a basic query on all tables looking for those that match the hContactId. Any ideas?
Well you can always use a union:
SELECT * FROM Table_name_1
WHERE hContactId = 200;
UNION
SELECT * FROM Table_name_2
WHERE hContactId = 200;
UNION
SELECT * FROM Table_name_3
WHERE hContactId = 200;
I have a Emplyee table as Follow,
https://i.stack.imgur.com/WjtM6.png
In every Updation(any column Delete,Update) ineed save that details to another table for security purpose.That tbale structure as following.
https://i.stack.imgur.com/Yv1YD.png
I can write a Code in my programe to do this job, but Can i write a trigger to Automatically saved old data to employee updation table using triger?
in a MySql that function availble, I dont Konw about MS SQL.
thank you!
i would suggest to create audit table similar to original table
IF NOT EXISTS
(SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[Audit]')
AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
CREATE TABLE Audit
(Type CHAR(1),
TableName VARCHAR(128),
PK VARCHAR(1000),
FieldName VARCHAR(128),
OldValue VARCHAR(1000),
NewValue VARCHAR(1000),
UpdateDate datetime,
UserName VARCHAR(128))
GO
Then work on the trigger as below, which can track, INSERT, UPDATE and DELETE operations.
CREATE TRIGGER TR_GUESTS_AUDIT ON dbo.IBIS_UnitSchedule FOR UPDATE
AS
DECLARE #bit INT ,
#field INT ,
#maxfield INT ,
#char INT ,
#fieldname VARCHAR(128) ,
#TableName VARCHAR(128) ,
#PKCols VARCHAR(1000) ,
#sql VARCHAR(2000),
#UpdateDate VARCHAR(21) ,
#UserName VARCHAR(128) ,
#Type CHAR(1) ,
#PKSelect VARCHAR(1000)
SELECT #TableName = 'dbo.IBIS_UnitSchedule'
-- date and user
SELECT #UserName = SYSTEM_USER ,
#UpdateDate = CONVERT (NVARCHAR(30),GETDATE(),126)
-- Action
IF EXISTS (SELECT * FROM inserted)
IF EXISTS (SELECT * FROM deleted)
SELECT #Type = 'U'
ELSE
SELECT #Type = 'I'
ELSE
SELECT #Type = 'D'
-- get list of columns
SELECT * INTO #ins FROM inserted
SELECT * INTO #del FROM deleted
-- Get primary key columns for full outer join
SELECT #PKCols = COALESCE(#PKCols + ' and', ' on')
+ ' i.' + c.COLUMN_NAME + ' = d.' + c.COLUMN_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk ,
INFORMATION_SCHEMA.KEY_COLUMN_USAGE c
WHERE pk.TABLE_NAME = #TableName
AND CONSTRAINT_TYPE = 'PRIMARY KEY'
AND c.TABLE_NAME = pk.TABLE_NAME
AND c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME
-- Get primary key select for insert
SELECT #PKSelect = COALESCE(#PKSelect+'+','')
+ '''<' + COLUMN_NAME
+ '=''+convert(varchar(100),
coalesce(i.' + COLUMN_NAME +',d.' + COLUMN_NAME + '))+''>'''
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk ,
INFORMATION_SCHEMA.KEY_COLUMN_USAGE c
WHERE pk.TABLE_NAME = #TableName
AND CONSTRAINT_TYPE = 'PRIMARY KEY'
AND c.TABLE_NAME = pk.TABLE_NAME
AND c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME
IF #PKCols IS NULL
BEGIN
RAISERROR('no PK on table %s', 16, -1, #TableName)
RETURN
END
SELECT #field = 0,
#maxfield = MAX(ORDINAL_POSITION)
FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = #TableName
WHILE #field < #maxfield
BEGIN
SELECT #field = MIN(ORDINAL_POSITION)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = #TableName
AND ORDINAL_POSITION > #field
SELECT #bit = (#field - 1 )% 8 + 1
SELECT #bit = POWER(2,#bit - 1)
SELECT #char = ((#field - 1) / 8) + 1
IF SUBSTRING(COLUMNS_UPDATED(),#char, 1) & #bit > 0
OR #Type IN ('I','D')
BEGIN
SELECT #fieldname = COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = #TableName
AND ORDINAL_POSITION = #field
SELECT #sql = '
insert Audit ( Type,
TableName,
PK,
FieldName,
OldValue,
NewValue,
UpdateDate,
UserName)
select ''' + #Type + ''','''
+ #TableName + ''',' + #PKSelect
+ ',''' + #fieldname + ''''
+ ',convert(varchar(1000),d.' + #fieldname + ')'
+ ',convert(varchar(1000),i.' + #fieldname + ')'
+ ',''' + #UpdateDate + ''''
+ ',''' + #UserName + ''''
+ ' from #ins i full outer join #del d'
+ #PKCols
+ ' where i.' + #fieldname + ' <> d.' + #fieldname
+ ' or (i.' + #fieldname + ' is null and d.'
+ #fieldname
+ ' is not null)'
+ ' or (i.' + #fieldname + ' is not null and d.'
+ #fieldname
+ ' is null)'
EXEC (#sql)
END
END
GO
Hi all I have written the following Procedure to display the results as pivot as per the requirement
DECLARE #values AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
SELECT #values = STUFF(
(
SELECT DISTINCT ',[' + ColumnName + ']'
FROM xTable
FOR xml path ('')
),1,1,'')
SET #query = 'SELECT viewName1.*, pValues.Code, ' + #values + ' FROM
(
SELECT Column1,Column2, Column3
FROM viewname
) aliasName
PIVOT
(
MAX(value)
FOR ColumnName in (' + #values + ')
) pValues INNER JOIN viewName1 ON pValues.Code = viewname.Code'
EXEC(#query)
But when the value and column names are same in my xTable and viewName1 I am getting that error how can I resolve this. I tried with alas but I am not getting the expected result so can some one help me.
Sample is I am having a ColumnName as TopBrand in my table xTable, this can be a value in my viewName1 like for X Column TopBrand can be a value.
I think you need to have a separate list for FOR and IN clauses and the former should include the alias:
DECLARE #valuesFor AS NVARCHAR(MAX),
#valuesIn AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
SELECT #valuesFor = STUFF(
(
SELECT DISTINCT N',pValues.[' + ColumnName + ']'
FROM xTable
FOR xml path ('')
),1,1,'')
SELECT #valuesIn = STUFF(
(
SELECT DISTINCT N',[' + ColumnName + ']'
FROM xTable
FOR xml path ('')
),1,1,'')
SET #query = N'SELECT viewName1.*, pValues.Code, ' + #valuesFor + N' FROM
(
SELECT Column1,Column2, Column3
FROM viewname
) aliasName
PIVOT
(
MAX(value)
FOR ColumnName in (' + #valuesIn + N')
) pValues INNER JOIN viewName1 ON pValues.Code = viewname.Code'
EXEC(#query)