当列名为字符串时,是否可以获取多列值
就像我有一个表Test
,我有列FirstName , LastName , Address
。
现在我想要获得所有三列的值,但我想使这个动态,以便我只传递字符串列名称我得到该列的值
示例
Select
(select column_name from metadata )
from source table
答案 0 :(得分:5)
将列名称作为参数传递
DECLARE @COLS NVARCHAR(MAX)
DECLARE @TABLE NVARCHAR(MAX)
SET @COLS = 'COL1,COL2'
SET @TABLE = 'TABLENAME'
现在执行查询
DECLARE @QRY NVARCHAR(MAX)
SET @QRY = 'SELECT (SELECT '+@COLS+' FROM '+@TABLE+') FROM sourcetable'
EXEC SP_EXECUTESQL @QRY
答案 1 :(得分:1)
您可以动态地在代码中构建查询。但是它需要健壮,以便它不易受SQL注入的影响。像这样:
string commandString = "select {0} from SomeTable";
SqlCommand command = new SqlCommand();
command.CommandText = string.Format(commandString, "selected column names");
command.EndExecuteReader();
在SQL中:
declare @query nvarchar(500)
set @query = replace('select 0 from author','0','column names from some parameter')
execute sp_executesql @query
更新2:这是否符合您的要求?
declare @query nvarchar(500)
DECLARE @columnNames varchar(1000)
set @columnNames = ''
SELECT @columnNames = @columnNames + column_name + ',' FROM metadata
set @query = replace('select 0 from source_table','0',SUBSTRING(@columnNames,0,LEN(@columnNames)-1))
execute sp_executesql @query
答案 2 :(得分:0)