本文介绍了SQL:返回列名称,其中列包含给定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道是否有我可以在 SQL Server 中运行的命令/存储过程,它会给我包含表中给定数据的列的名称.
i was wondering if there was a command/stored proc i can run in SQL Server that will give me the names of columns that contain given data within a table.
因此,如果我要查询,请给我此表中包含值 75 的所有列.我不想要该行.只是表中的列名...这可能吗?
So if i was to query, give me all the columns in this table, that contain the value 75. i wouldnt want the row. just the column name within the table... is this possible?
推荐答案
-- input parameters (guessing on type for @value):
DECLARE
@schema SYSNAME = N'dbo',
@table SYSNAME = N'z',
@value VARCHAR(64) = '75';
-- now, inside the procedure body:
DECLARE @sql NVARCHAR(MAX) = N'SELECT ''cols:'' + STUFF(''''';
SELECT @sql += N'
+ CASE WHEN EXISTS (SELECT 1 FROM '
+ QUOTENAME(@schema) + '.' + QUOTENAME(@table)
+ ' WHERE TRY_CONVERT(VARCHAR(64), ' + QUOTENAME(c.name)
+ ') = @value) THEN '', ' + c.name + ''' ELSE '''' END'
FROM sys.tables AS t
INNER JOIN sys.columns AS c
ON t.[object_id] = c.[object_id]
INNER JOIN sys.schemas AS s
ON t.[schema_id] = s.[schema_id]
WHERE t.name = @table AND s.name = @schema;
SET @sql += N', 1, 1, '''');'
PRINT @sql;
--EXEC sp_executesql @sql, N'@value VARCHAR(64)', @value;
当您对输出感到满意时,取消注释 EXEC
.
When you are happy with the output, uncomment the EXEC
.
让我们考虑一个简单的表格:
So let's consider a simple table:
CREATE TABLE dbo.floob
(
a INT,
b VARCHAR(32),
c VARBINARY(22),
d DATE,
e DATETIME,
f ROWVERSION
);
INSERT dbo.floob(a,b,c,d,e) VALUES
( 75, 'foo', 0x00, GETDATE(), GETDATE()),
( 21, '75', 0x00, GETDATE(), GETDATE());
现在,一个基于上述代码的存储过程:
Now, a stored procedure based on the above code:
CREATE PROCEDURE dbo.FindStringInAnyColumn
@schema SYSNAME = N'dbo',
@table SYSNAME,
@value VARCHAR(64)
AS
BEGIN
SET NOCOUNT ON;
DECLARE @sql NVARCHAR(MAX) = N'SELECT ''cols:'' + STUFF(''''';
SELECT @sql += N'
+ CASE WHEN EXISTS (SELECT 1 FROM '
+ QUOTENAME(@schema) + '.' + QUOTENAME(@table)
+ ' WHERE TRY_CONVERT(VARCHAR(64), ' + QUOTENAME(c.name)
+ ') = @value) THEN '', ' + c.name + ''' ELSE '''' END'
FROM sys.tables AS t
INNER JOIN sys.columns AS c
ON t.[object_id] = c.[object_id]
INNER JOIN sys.schemas AS s
ON t.[schema_id] = s.[schema_id]
WHERE t.name = @table AND s.name = @schema;
SET @sql += N', 1, 1, '''');'
EXEC sp_executesql @sql, N'@value VARCHAR(64)', @value;
END
GO
示例用法:
EXEC dbo.FindStringInAnyColumn @table = N'floob', @value = '75';
输出:
Cols: a, b
这篇关于SQL:返回列名称,其中列包含给定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!