Create function that can be run with any database - sql-server

How can I create a function that can be run against any database on my server?
Here's an example, I want to specify a column name to search for, and which database to search in:
CREATE FUNCTION dbo.fn_FindColumnsInAllTables
(
#ColumnName NVARCHAR(255)
)
RETURNS TABLE
AS
RETURN
(
SELECT
c.name AS 'ColumnName'
,t.name AS 'TableName'
FROM
sys.columns c
JOIN
sys.tables t
ON
c.object_id = t.object_id
WHERE
c.name LIKE '%' + #ColumnName + '%'
)

Taking the excellent advice from HLGEM to use a procedure instead this is quite easy. This example not only works it is also sql injection proof. I use QUOTENAME around the database name itself and then parameterize the column name in the dynamic sql.
create procedure FindColumn
(
#DBName sysname
, #ColName sysname
) as
declare #SQL nvarchar(max);
if exists(select * from sys.databases where name = #DBName)
begin
set #SQL = 'select t.name as TableName
, c.name as ColumnName
from ' + QUOTENAME(#DBName) + '.sys.tables t
join ' + QUOTENAME(#DBName) + '.sys.columns c on c.object_id = t.object_id
where c.name = #ColName'
exec sp_executesql #SQL, N'#ColName sysname', #ColName = #ColName
end
else
select 'Database not found'
GO
exec FindColumn 'YourDatabaseName', 'YourColumn'

Related

How to get all the table names and distinct values in a particular column from a database for the tables which have a column using SQL Server

I am trying to get all the table names and the values present in a particular column if the column is present in the database. For the tables without the column ignore those.
For example: Find all the table name and values from a column 'last_refresh_date' in a database for all the tables with last_refresh_date column.
The code I tried is:
EXEC sp_MSforeachtable 'SELECT distinct ''?'' TableName, last_refresh_date FROM ?'
I get an error as some of the tables doesn't have the column name 'last_refresh_date' in it.
Thanks for the help in advance
I'm going to assume you are using a recent version of SQL Server, and thus have access to STRING_AGG, if not you'll need to use the "old" FOR XML PATH method.
Anyway, you achieve this with a little bit of dynamic SQL, and UNION ALL. I assume you want the table and schema names as well:
DECLARE #SQL nvarchar(MAX),
#ColumnName sysname = N'YourColumnName',
#CRLF nchar(2) = CHAR(13) + CHAR(10);
DECLARE #Delimiter nvarchar(30) = #CRLF + N'UNION ALL' + #CRLF
SET #SQL = (SELECT STRING_AGG(N'SELECT N' + QUOTENAME(s.[name],'''') + N' AS SchemaName, N' + QUOTENAME(t.[name],'''') + N' AS TableName, ' + QUOTENAME(c.[name]) + N' FROM ' + QUOTENAME(s.[name]) + N'.' + QUOTENAME(t.[name]), #Delimiter) WITHIN GROUP (ORDER BY t.object_id)
FROM sys.schemas s
JOIN sys.tables t ON s.schema_id = t.schema_id
JOIN sys.columns c ON t.object_id = c.object_id
WHERE c.[name] = #ColumnName)
EXEC sys.sp_executesql #SQL;

I have this stored procedure and I want to revise it to be to rebuild more than one index in SQL

I have this stored procedure and I want to revise it to be to rebuild more than one index.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [Landing].[usp_IndexDisableRebuild]
(#Schema_Name VARCHAR(256),
#Table_Name VARCHAR(256),
#Task_Name VARCHAR(256))
AS
-- Set to get the dynamic Script for
DECLARE #sql VARCHAR(MAX)
SET #sql = (SELECT 'ALTER INDEX ' + QUOTENAME(I.name) + ' ON ' + QUOTENAME(SCHEMA_NAME(T.schema_id))+'.'+ QUOTENAME(T.name) + #Task_Name FROM sys.indexes I INNER JOIN sys.tables T ON I.object_id = T.object_id INNER Join sys.schemas s ON s.schema_id = t.schema_id WHERE I.type_desc = 'NONCLUSTERED' AND I.name IS NOT NULL --AND I.is_disabled = 0 AND t.name = #Table_Name AND s.name = #Schema_Name )
-- Execute the dynamic SQL
EXEC (#sql)
I agree with the comments that you should consider using Ola Hallengren's SQL Server Maintenance Solution.
That being said, you could change your proc like to example below. In addition to correcting the subquery error, this uses the proper data types. Not sure what you want to do with #Task_Name so I just appended the value as a comment.
ALTER PROCEDURE [Landing].[usp_IndexDisableRebuild]
#Schema_Name sysname,
#Table_Name sysname,
#Task_Name VARCHAR(256)
AS
DECLARE #SQL nvarchar(MAX);
SET #SQL = (
SELECT 'ALTER INDEX ' + QUOTENAME(I.name)
+ ' ON ' + QUOTENAME(SCHEMA_NAME(T.schema_id))+'.'+ QUOTENAME(T.name) + ' REBUILD;
--' + #Task_Name + '
'
FROM sys.indexes I
INNER JOIN sys.tables T ON I.object_id = T.object_id
INNER Join sys.schemas s ON s.schema_id = t.schema_id
WHERE I.type_desc = 'NONCLUSTERED'
AND I.name IS NOT NULL
AND I.is_disabled = 0
AND t.name = #Table_Name
AND s.name = #Schema_Name
FOR XML PATH(''), TYPE).value('.','nvarchar(MAX)');
--PRINT #SQL;
EXECUTE sp_executesql #SQL;
GO

select all databases in sysobjects that have a table named 'mytable' regardless of schema?

For a given sql 2000 - 2008 server I want to find any table named dbo.[MyTable] on that server. In addition, how do I find all databases that have a table named [dbo].[MyTable] and [AnySchemaName].[MyTable]. Is there a simple sp_ command like spTables MyTable? Or 'sp_AllDatabaseTable [MyTable]'?
I want to print it out like:
ServerName Database SchemaName MyTable Date Created
----------- --------- ----------- --------- -------------
Thx
I really would prefer a solution that does not use either CURSORS nor sp_msforeachdb.
The solution below is gives you an idea, and you can adapt it to your own needs.
USE [master]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
BEGIN TRY
SET NOCOUNT ON
SET DATEFORMAT DMY
SET DEADLOCK_PRIORITY NORMAL;
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
DECLARE #log NVARCHAR(MAX)
,#vCrlf CHAR(2);
SELECT #log = ''
,#vCrlf = CHAR(13)+CHAR(10);
DECLARE #SQL NVARCHAR(MAX)
BEGIN TRY DROP TABLE #OBJECTS END TRY BEGIN CATCH END CATCH
CREATE TABLE #OBJECTS(
DB_ID INT,
OBJECT_ID INT,
S_NAME SYSNAME,
NAME SYSNAME,
ROW_COUNT INT,
STATISTICS_UPDATED DATETIME)
SELECT #SQL = '
SELECT db_id=db_id(),
o.object_id,
s_name=s.name,
o.name,
ddps.row_count
,[Statistics_Updated]=STATS_DATE(I.OBJECT_ID,I.INDEX_ID)
FROM sys.indexes AS i
INNER JOIN sys.objects AS o ON i.OBJECT_ID = o.OBJECT_ID
INNER JOIN sys.schemas s ON s.schema_id = o.schema_id
INNER JOIN sys.dm_db_partition_stats AS ddps ON i.OBJECT_ID = ddps.OBJECT_ID
AND i.index_id = ddps.index_id
WHERE i.index_id < 2
AND o.is_ms_shipped = 0
'
set #SQL = (
SELECT STUFF(
(SELECT N' ' + ' USE ' + QUOTENAME(name) +';' + #vCrlf + #SQL + #vCrlf
FROM SYS.DATABASES SD
WHERE SD.STATE_DESC = 'ONLINE' -->Skips the database if it is not online
AND SD.COMPATIBILITY_LEVEL > 80
AND SD.database_id > 3 -- NO MASTER NOR TEMPDB NOR MODEL
FOR XML PATH(''),TYPE)
.value('text()[1]','nvarchar(max)'),1,2,N'')
)
INSERT INTO #OBJECTS
( [db_id],
[object_id],
[s_name],
[name],
[row_count],
[Statistics_Updated]
)
EXECUTE MASTER.DBO.sp_executesql #SQL
SELECT * FROM #OBJECTS
--WHERE NAME = 'THE NAME THAT I AM LOOKING FOR'
END TRY
BEGIN CATCH
PRINT '--EXCEPTION WAS CAUGHT--' + CHAR(13) +
'THE ERROR NUMBER:' + COALESCE(CAST ( ERROR_NUMBER() AS VARCHAR), 'NO INFO') + CHAR(13)
PRINT 'SEVERITY: ' + COALESCE(CAST ( ERROR_SEVERITY() AS VARCHAR), 'NO INFO') + CHAR(13) +
'STATE: ' + COALESCE(CAST ( ERROR_STATE() AS VARCHAR), 'NO INFO') + CHAR(13)
PRINT 'PROCEDURE: ' + COALESCE(CAST ( COALESCE(ERROR_PROCEDURE(),'NO INFO') AS VARCHAR), 'NO INFO') + CHAR(13) +
'LINE NUMBER: ' + COALESCE(CAST ( ERROR_LINE() AS VARCHAR), 'NO INFO') + CHAR(13)
PRINT 'ERROR MESSAGE: '
PRINT CAST ( COALESCE(ERROR_MESSAGE(),'NO INFO') AS NTEXT)
END CATCH;
I prefer a set based approach:
Declare #TableName as Varchar(255)
Set #TableName = '<MyTableName>'
Declare #SQL as Varchar(max)
Select #SQL = Coalesce(#SQL + '
', '') +
CASE
WHEN Row_Number() Over (Order by Database_ID) = 1
THEN ''
ELSE
'UNION ALL '
END +
'SELECT
''' + d.Name + ''' as DatabaseName
, s.Name as SchemaName
, o.Name as TableName
FROM ' + d.Name +'.Sys.Objects o
INNER JOIN ' + d.Name + '.Sys.Schemas s
ON o.Schema_ID = s.Schema_ID
WHERE o.Name like ''' + #TableName + ''''
FROM sys.databases d
where d.Name not like 'ReportServer%'
and d.Name not like 'SSISPackageRegistry'
Print #SQL
EXEC(#SQL)
Of course, you can use sp_msforeachdb for this purpose but you need to remember that fhis function is neither documented nor officially supported. Also, sometimes it breaks. More about it here Making a more reliable and flexible sp_MSforeachdb
You can use this script to search table by name in all databases.
I took it from Find table in every database of SQL server
DECLARE #TableName VARCHAR(256)
SET #TableName='YOUR_TABLE_NAME'
DECLARE #DBName VARCHAR(256)
DECLARE #varSQL VARCHAR(512)
DECLARE #getDBName CURSOR
SET #getDBName = CURSOR FOR
SELECT name
FROM sys.databases
CREATE TABLE #TmpTable (DBName VARCHAR(256),
SchemaName VARCHAR(256),
TableName VARCHAR(256),
create_date date, modify_date date)
OPEN #getDBName
FETCH NEXT
FROM #getDBName INTO #DBName
WHILE ##FETCH_STATUS = 0
BEGIN
SET #varSQL = 'USE ' + #DBName + ';
INSERT INTO #TmpTable
SELECT '''+ #DBName + ''' AS DBName,
SCHEMA_NAME(schema_id) AS SchemaName,
name AS TableName,
create_date, modify_date
FROM sys.tables
WHERE name LIKE ''%' + #TableName + '%''' --WHERE name = '' + #TableName + ''' /* if you want to search by exact table name*/
EXEC (#varSQL)
FETCH NEXT
FROM #getDBName INTO #DBName
END
CLOSE #getDBName
DEALLOCATE #getDBName
SELECT *
FROM #TmpTable
DROP TABLE #TmpTable
Also, you may want to read this Find table name in all objects of all databases
I'd have said
sp_msforeachdb 'Select * from Sysobjects where name=''MyTable'''
But you don't need to, sysobjects is in the master table and does it for all databases anyway.
You should be able find the other columns easily enough.

Find table name in all objects of all databases

I have a system with multiple databases and client applications. All databases are at one SQL Server instance. They have been developed by different people at different time. So if some error occur it is pritty hard to find in which procedure or trigger the data was modified.
Now I use this script, which I found on this site:
SELECT DISTINCT ISNULL(sd.referenced_schema_name+'.','')+ OBJECT_NAME(sd.referenced_id)TableName,
OBJECT_NAME(sd.referencing_id)Ref_Object,
CASE WHEN OBJECTPROPERTYEX(sd.referencing_id,N'IsUserTable')= 1
THEN'Table'
WHEN OBJECTPROPERTYEX(sd.referencing_id,N'IsTableFunction')= 1
THEN'Function'
WHEN OBJECTPROPERTYEX(sd.referencing_id,N'IsTableFunction')= 1
THEN'Function'
WHEN OBJECTPROPERTYEX(sd.referencing_id,N'IsScalarFunction')=1
THEN'Function'
WHEN OBJECTPROPERTYEX(sd.referencing_id,N'IsTrigger')= 1
THEN'Trigger'
WHEN OBJECTPROPERTYEX(sd.referencing_id,N'IsView')= 1
THEN'View'
WHEN OBJECTPROPERTYEX(sd.referencing_id,N'IsUserTable')= 1
THEN'Table'
WHEN OBJECTPROPERTYEX(sd.referencing_id,N'IsProcedure')= 1
THEN'Procedure'
WHEN OBJECTPROPERTYEX(sd.referencing_id,N'IsIndexed')= 1
THEN'Index'
WHEN OBJECTPROPERTYEX(sd.referencing_id,N'IsForeignKey')= 1
THEN'ForeignKey'
WHEN OBJECTPROPERTYEX(sd.referencing_id,N'IsPrimaryKey')= 1
THEN'PrimaryKey'
END AS Ref_Object_Name
FROM sys.sql_expression_dependencies SD
INNER JOIN sys.objects obj
ON obj.object_id=sd.referenced_id
WHERE obj.is_ms_shipped= 0
and referenced_id=object_id('TABLE_NAME') /*Where one can Replace table Name*/
AND obj.type_desc='USER_TABLE'
ORDER BY TableName,Ref_Object,Ref_Object_Name
But this script seems to work only for the database to which the table belong.
I want to get for a specified table name (or even better for an object) list of all objects of all databases in which the specified table name met:
Database_Name SchemaName ObjectName ObjectKind
Thanks.
DECLARE #table_name SYSNAME = N'%';
DECLARE #sql NVARCHAR(MAX) = N'';
SELECT #sql += 'SELECT DISTINCT Database_Name = ''' + QUOTENAME(name) + ''',
COALESCE(sd.referenced_schema_name +''.'', '''')+ o.name AS TableName,
r.name AS Ref_Object,
r.type_desc AS Ref_Object_Name
FROM ' + QUOTENAME(name) + '.sys.sql_expression_dependencies AS sd
INNER JOIN ' + QUOTENAME(name) + '.sys.objects AS o
ON o.object_id = sd.referenced_id
INNER JOIN ' + QUOTENAME(name) + '.sys.objects AS r
ON sd.referencing_id = r.object_id
WHERE o.is_ms_shipped = 0
and referenced_id = o.object_id
AND o.type_desc = ''USER_TABLE''
AND o.name LIKE ''' + #table_name + '''
UNION ALL
'
FROM sys.databases
WHERE database_id BETWEEN 5 AND 32766;
SET #sql = LEFT(#sql, LEN(#sql)-11)
+ 'ORDER BY Database_Name, TableName,Ref_Object,Ref_Object_Name';
EXEC sp_executesql #sql;
EDIT
The above will find all the references within each database, but won't find cross-database references. It took a little playing, and the output isn't precisely what you wanted, but I think it makes it more self-explanatory:
DECLARE #table_name SYSNAME = N'%'; -- find all
CREATE TABLE #d
(
db SYSNAME,
[object_id] INT,
sch SYSNAME,
obj SYSNAME,
ref_db NVARCHAR(128),
ref_sch NVARCHAR(128),
ref_obj NVARCHAR(128),
ref_object_id INT,
type_desc SYSNAME
);
DECLARE #sql NVARCHAR(MAX) = N'';
SELECT #sql += 'SELECT ''' + QUOTENAME(name) + ''',
d.referencing_id,
QUOTENAME(s.name),
QUOTENAME(o.name),
QUOTENAME(d.referenced_database_name),
QUOTENAME(d.referenced_schema_name),
QUOTENAME(d.referenced_entity_name),
d.referenced_id,
o.type_desc
FROM ' + QUOTENAME(name)
+ '.sys.sql_expression_dependencies AS d
INNER JOIN ' + QUOTENAME(name)
+ '.sys.objects AS o
ON d.referencing_id = o.[object_id]
INNER JOIN '
+ QUOTENAME(name) + '.sys.schemas AS s
ON o.[schema_id] = s.[schema_id]
WHERE d.referenced_entity_name LIKE ''' + #table_name + '''
UNION ALL
'
FROM sys.databases WHERE database_id BETWEEN 5 AND 32766;
SET #sql = LEFT(#sql, LEN(#sql)-11);
INSERT #d EXEC sp_executesql #sql;
SELECT
db+'.'+sch+'.'+obj,
' (' + type_desc + ') references => ',
COALESCE(ref_db, db)+'.'+ref_sch+'.'+ref_obj
FROM #d;
GO
DROP TABLE #d;
GO
Sample output:
[db1].[dbo].[foo] (SQL_STORED_PROCEDURE) references => [db2].[dbo].[bar]
[db1].[dbo].[xyz] (SQL_STORED_PROCEDURE) references => [db1].[dbo].[table_xyz]
This should help you get started
create table ##tbData (
DatabaseName Varchar(64),
objectName varchar(128),
ObjectKind varchar(128)
)
go
EXEC sp_Msforeachdb "use [?];
insert ##tbData select db_name(),so.name,so.xtype from sysobjects so"
select * from ##tbdata
Essentially, build a table and the SQL statement you want to use, then use the undocumented sp_MSforEachdb to load the table from every database
You could look at something like sp_MSForeachdb and call the above query each of those databases.

How do I rename my constraints

I renamed a table in my database with
EXEC sp_rename 'tblOldAndBusted', 'tblNewAndShiny'
and all the foreign key constraints were updated to the new table name, but they're still named based on the old table name. For example, I now have FK_tblOldAndBusted_tblTastyData but I'd like to have FK_tblNewAndShiny_tblTastyData.
Is there an easy way to script this?
Also, am I being too anal? I know the database works fine with the old table name in the constraints, but it feels like broken windows.
Try:
exec sp_rename 'FK_tblOldAndBusted_tblTastyData', 'FK_tblNewAndShiny_tblTastyData', 'object'
Also, there is a bug regarding renaming such things when you deal with non-default schema.
Cannot rename a default constraint for a table in a schema which is not dbo by rsocol #Microsoft Connect
After some more digging, I found that it actually has to be in this form:
EXEC sp_rename N'schema.MyIOldConstraint', N'MyNewConstraint', N'OBJECT'
Source
I am not a big fan of cursors and this can be written much more simply.
DECLARE #SQLCmd varchar(MAX) = ''
SELECT
#SQLCmd += 'EXEC sp_rename ''' + dc.name + ''', ''DF' +
OBJECT_NAME( dc.parent_object_id ) + c.name + ''', ''OBJECT'';'
FROM
sys.default_constraints dc
JOIN sys.columns c
ON c.object_id = dc.parent_object_id
AND c.column_id = dc.parent_column_id
WHERE
dc.name != 'DF' + object_name( dc.parent_object_id ) + c.name
AND OBJECT_NAME( dc.parent_object_id ) != 'dtproperties'
EXEC( #SqlCmd )
If anyone is interested, I just had to rename all the default constraints for the an audit field named "EnteredDate"to a specific pattern. Update and replace as needed. I hope this helps and might be a starting point.
DECLARE #TableName VARCHAR(255), #ConstraintName VARCHAR(255)
DECLARE constraint_cursor CURSOR
FOR
select b.name, c.name from
sys.all_columns a
inner join
sys.tables b
on
a.object_id = b.object_id
inner join
sys.default_constraints c
on a.default_object_id = c.object_id
where
b.name <> 'sysdiagrams'
and a.name = 'EnteredDate' -- column name
and b.type = 'U'
OPEN constraint_cursor
FETCH NEXT FROM constraint_cursor INTO #TableName, #ConstraintName
WHILE ##FETCH_STATUS = 0
BEGIN
DECLARE #SqlScript VARCHAR(255) = ''
SET #SqlScript = 'sp_rename ' + #ConstraintName + ', ''DF_' + #TableName + '_EnteredDate'', ''object'''
EXEC(#SqlScript)
SELECT #TableName, #ConstraintName, 'DF_' + #TableName + '_EnteredDate', #SqlScript
FETCH NEXT FROM constraint_cursor INTO #TableName, #ConstraintName
END
CLOSE constraint_cursor;
DEALLOCATE constraint_cursor;
https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-rename-transact-sql?view=sql-server-ver15
If the object to be renamed is a constraint, object_name must be in the form schema.constraint.
So the correct form is:
exec sp_rename 'schema.oldname','newname', 'object'
Prefix the oldname with the schema.
Do not prefix the newname with the schema...
If there are too many to rename, how about export to dump, edit the dump in any text editor of choice to replace the table name, and then restore from dump? I mean export the dump of only constraints, not all.
Based user906573's script. Generate a script to rename all defaults in the database. Useful for correcting constraints that weren't explicitly named at create time.
--
-- Generates a script to rename defaults to the pattern DF_tablename_columnname
--
DECLARE #TableName VARCHAR(255), #ConstraintName VARCHAR(255), #ColumnName varchar(255), #SchemaName varchar(255)
DECLARE constraint_cursor CURSOR
FOR
select b.name, c.name, a.name, sc.name
from sys.all_columns a
inner join sys.tables b on a.object_id = b.object_id
join sys.schemas sc on b.schema_id = sc.schema_id
inner join sys.default_constraints c on a.default_object_id = c.object_id
where
b.name <> 'sysdiagrams'
and b.type = 'U'
OPEN constraint_cursor
FETCH NEXT FROM constraint_cursor INTO #TableName, #ConstraintName, #ColumnName, #SchemaName
WHILE ##FETCH_STATUS = 0
BEGIN
DECLARE #SqlScript VARCHAR(255) = ''
SET #SqlScript = 'sp_rename ''' + #SchemaName + '.' + #ConstraintName + ''', ''' + #SchemaName + '.DF_' + #TableName + '_' + #ColumnName + ''', ''object''' + char(13) + char(10) + 'GO' + char(13) + char(10)
--EXEC(#SqlScript)
print #sqlscript
FETCH NEXT FROM constraint_cursor INTO #TableName, #ConstraintName, #ColumnName, #SchemaName
END
CLOSE constraint_cursor;
DEALLOCATE constraint_cursor;
I know this thread is a bit dated but I wanted to post my alternative to #foxfire's answer as I made some modifications to it. Made it take a smaller chunk of the names as I ran into database where there were so many renames it made the #sql truncate. I also added error handling to break out as well as schema names for handling different schemas other than dbo. I chose not to use a begin try so it could be used among multiple sql server versions. The where clause can be manipulated to fulfill the OP's original intent.
BEGIN TRAN
DECLARE #sql varchar(MAX) = '...'
WHILE LEN(#sql) > 0 BEGIN
SET #sql = '';
SELECT TOP 50 #sql = #sql
+ 'EXEC sp_rename N''' + SCHEMA_NAME(dc.[schema_id]) + '.' + dc.name
+ ''', N''DF_' + OBJECT_NAME(dc.parent_object_id) + '_' + c.name
+ ''', ''OBJECT'';' + CHAR(10)
FROM sys.default_constraints dc
inner join sys.columns c
ON c.object_id = dc.parent_object_id AND c.column_id = dc.parent_column_id
WHERE dc.name LIKE 'DF[_][_]%' -- rename any auto named defaults
PRINT #sql
EXEC(#sql)
IF ##ERROR <> 0 BEGIN
IF ##TRANCOUNT > 0 ROLLBACK TRAN
BREAK;
END
END
IF ##TRANCOUNT > 0 COMMIT TRAN
--IF ##TRANCOUNT > 0 ROLLBACK TRAN

Resources