我试图编写一个存储过程,它将根据两个输入参数返回一个特定的值。问题是尝试使其中一个参数引用一列。
这是我的表:
CityID CityName London Paris
----------- -------------------- --------------------------------------- --
1 London 0 60
2 Paris 50 0
3 Berlin 90 60
4 Madrid 150 90
5 Dublin 30 80
6 Rome 75 88
是否可以按以下方式编写存储过程:
CREATE PROCEDURE Price (@city1, @city2)
AS
SELECT @city2
FROM dbo.MyTable
WHERE CityName = @city1
答案 0 :(得分:1)
我尝试运行动态SQL语句之前做了类似的事情来验证列名的存在:
create procedure dbo.GetPrice(@city nvarchar(50), @column nvarchar(200)) as
begin
if (not exists (select *
from sys.columns
where object_id = object_id('dbo.MyTable') and name = @column))
return;
else begin
declare @sql nvarchar(max) =
'SELECT [' + @column + '] FROM dbo.MyTable WHERE CityName = ''' + @city + '''';
execute sp_ExecuteSQL @sql;
end;
end;
答案 1 :(得分:0)
您必须使用动态sql。
CREATE PROC Price (@City1, @City2)
AS
BEGIN
DECLARE @Sql NVARCHAR(MAX)
SET @Sql = 'SELECT ' + @City2 + ' FROM dbo.MyTable WHERE CityName = ''' +
@City1 + ''''
EXEC sp_execute @Sql
END
答案 2 :(得分:0)
创建PROCEDURE [dbo]。[USP_Price] @ city1 Varchar, ------------------------------------------------ @ City2 VARCHAR(MAX)= NULL OUT
AS BEGIN
SELECT @city2
FROM dbo.MyTable
WHERE CityName = @city1
END
---创建存储过程,如果使用的是sql server, 右键单击存储过程,然后单击“执行存储过程” 输入city1值,同时为城市2选择null 并执行