我正在尝试从SQL过程中检索一堆信息。它应该接收两个参数,一个参数是表名,另一个是正确的值。有什么办法可以找回吗?
这是我到目前为止创建的查询:
CREATE PROCEDURE SP_Positions_Filtered
@Parameter VARCHAR(200),
@Id VARCHAR(50)
AS
SELECT
POSITION.*,
COALESCE((SELECT Category.Name
FROM Category
WHERE Category.Id = POSITION.Area), POSITION.Area) AS AreaName,
COALESCE((SELECT Country.Name
FROM Country
WHERE Country.Id = POSITION.Country), POSITION.Country) AS CountryName,
COALESCE((SELECT Department.Name
FROM Department
WHERE Department.Id = POSITION.Department), POSITION.Department) AS DepartmentName,
COALESCE((SELECT City.Name
FROM City
WHERE City.Id = POSITION.City), POSITION.City) AS CityName,
COALESCE((SELECT Salary.Data_Range
FROM Salary
WHERE Salary.Id = POSITION.Wage), POSITION.Wage) AS SalaryRange
FROM
POSITION
WHERE
(SELECT DISTINCT name FROM sys.columns WHERE name = @Parameter) = @Id
有人可以帮我解决这个问题吗?
谢谢。
答案 0 :(得分:0)
您可以使用存储过程中的动态查询来实现此目的。 参见下面的示例:
CREATE Procedure FC_Sample
@TableName Varchar (100)
AS
BEGIN
DECLARE @query NVARCHAR(MAX);
set @query = 'SELECT * from' + ' ' + @TableName
EXECUTE sp_executesql @query
END
您可以执行以下存储过程:
EXEC FC_Sample 'ACIChemical'
希望这就是您想要的。
注意:我在“答案”部分中给出了答案,因为我在此问题上没有50的声誉才能发表评论,否则在发布答案之前我会问更多的问题。