将一个查询值传递给SQL Server中的另一个查询



我需要将一个查询值作为"传递给另一个查询;表名";以及";列名";像低于

SELECT Value1 AS [MyTableName],Value2 AS [MyColName]
FROM MyTable

将以上结果传递到以下查询,如下所示。

SELECT * FROM [MyTableName]
WHERE ColumnValue = MyColName

在这种情况下,根据上述结果,MyTableName为Value1,MyColName为Value2。是否可以将上述结果组合成一个查询。

您需要使用动态sql。

为了防止注射,我们将使用这些:1( sp_executesql,这样我们就可以执行3(2( 系统对象(即表和列(名称的引号3( 通过参数传递列值

declare 
@mytablename nvarchar(128)
,@mycolname nvarchar(128)
,@mycolvalue nvarchar(max) -- or whatever your column type is
,@stmt nvarchar(max)
,@params nvarchar(max)
select @mytablename=quotename(Value1),@mycolname=quotename(Value2) AS [MyColName]
FROM MyTable
set @mycolvalue = 'myColValueData' -- or whatever the value is
set @stmt=
N'select * from '+@mytablename
+nchar(13)+nchar(10)+'where '+@mycolname+' = @mycolvalue'
set @params='@mycolvalue nvarchar(max)'  -- or whatever your column type is
exec sp_executesql(@stmt,@params,@mycolvalue=@mycolvalue)

最新更新