如何创建可以对我服务器上的任何数据库运行的函数?
这是一个例子,我想指定要搜索的列名,以及要搜索的数据库:
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 + '%'
)
答案 0 :(得分:2)
根据HLGEM的优秀建议改为使用程序,这很容易。这个例子不仅适用于sql注入证明。我在数据库名称周围使用QUOTENAME,然后在动态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'