简体   繁体   English

从查询中检索信息,其中表名和值是参数SQL

[英]Retrieve info from a query where table name and value are parameters SQL

I am trying to retrieve a bunch of info from SQL procedure. 我正在尝试从SQL过程中检索一堆信息。 It should receive two parameters, one of the parameters is a table name and the other is the value properly. 它应该接收两个参数,一个参数是表名,另一个是正确的值。 Is there any way to retrieve that? 有什么办法可以找回吗?

This is the query I've created so far: 这是我到目前为止创建的查询:

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

Could somebody help me out with this issue? 有人可以帮我解决这个问题吗?

Thanks in advance. 提前致谢。

You can achieve this using the Dynamic query inside the store procedure. 您可以使用存储过程中的动态查询来实现此目的。 see example below: 请参见下面的示例:

CREATE Procedure FC_Sample
@TableName Varchar (100) AS BEGIN DECLARE @query NVARCHAR(MAX); set @query = 'SELECT * from' + ' ' + @TableName EXECUTE sp_executesql @query END

And you can execute the Stored procedure as below: 您可以执行以下存储过程:

EXEC FC_Sample 'ACIChemical'

Hope this is what you are looking for. 希望这是您想要的。

NOTE: I am giving it in the Answer section as i don't have 50 reputation to comment on this question else i would have asked more question before posting the answer. 注意:我在“答案”部分中给出了该答案,因为我没有50个声誉可以对此问题发表评论,否则我在发布答案之前会问更多的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM