我可以将列名从select语句更改为从存储过程传入​​的参数吗?

时间:2022-09-09 08:50:13

I have a stored procedure takes in a parameter @phonename and I want to find out the property of the phone from the database. After I get the property from the database I would like to change the title of the column "Property" to the phone name that gets passed in from the stored procedure. For example, can I do

我有一个存储过程接受参数@phonename,我想从数据库中找出手机的属性。从数据库中获取属性后,我想将“Property”列的标题更改为从存储过程传入​​的电话名称。例如,我可以吗

Select property as @phonename
from property
join phone on property.Phid = phone.Phid
where phoneid = (select phid from phone where name = @phonename)

1 个解决方案

#1


1  

Well, it is posible, although not recommended...

嗯,它是可行的,虽然不推荐......

You could use dynamic sql:

你可以使用动态sql:

DECLARE @command varchar(1000)
DECLARE @phonename varchar(100)
SET @phonename = 'Aaron'
SET @command = 'SELECT myColumn AS ' + @phonename + ' FROM myTable WHERE name = ' + @phonename
EXEC (@command)

See: https://www.mssqltips.com/sqlservertip/1160/execute-dynamic-sql-commands-in-sql-server/

NOTE: If your planning to use something like this in a production environment please think about the possibilites of SQL Injection. You might be safer by applying those name changes in your application code instead of in SQL.

注意:如果您计划在生产环境中使用此类内容,请考虑SQL注入的可能性。通过在应用程序代码中而不是在SQL中应用这些名称更改,可能会更安全。

See: https://www.w3schools.com/sql/sql_injection.asp

#1


1  

Well, it is posible, although not recommended...

嗯,它是可行的,虽然不推荐......

You could use dynamic sql:

你可以使用动态sql:

DECLARE @command varchar(1000)
DECLARE @phonename varchar(100)
SET @phonename = 'Aaron'
SET @command = 'SELECT myColumn AS ' + @phonename + ' FROM myTable WHERE name = ' + @phonename
EXEC (@command)

See: https://www.mssqltips.com/sqlservertip/1160/execute-dynamic-sql-commands-in-sql-server/

NOTE: If your planning to use something like this in a production environment please think about the possibilites of SQL Injection. You might be safer by applying those name changes in your application code instead of in SQL.

注意:如果您计划在生产环境中使用此类内容,请考虑SQL注入的可能性。通过在应用程序代码中而不是在SQL中应用这些名称更改,可能会更安全。

See: https://www.w3schools.com/sql/sql_injection.asp