I am trying to retrieve a bunch of info from SQL procedure. 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.