SQL 2008
您好,
我在SQL中必须完成一项相当不同的任务。它比这更复杂,但我会试着让它变得简单。
我需要以某种方式动态地选择列。像这样:
declare @ColName varchar(50)
select @ColName = 'Column1' --This is an actual column name in a real table called 'MyTable'
select @ColName from MyTable where Column2 = 123
有没有办法做这样的事情?任何帮助或方向将不胜感激!
谢谢, 杰森
答案 0 :(得分:1)
您需要动态SQL,但请先阅读The Curse and Blessings of Dynamic SQL以确保您不会为SQL Injection
打开自己
答案 1 :(得分:1)
DECLARE @colNameIn AS varchar(50) = 'Column1'
DECLARE @template AS varchar(MAX) = 'select {@ColName} from MyTable where Column2 = 123' -- This template can be expanded
-- Protect yourself from injection or invalid columns:
DECLARE @ColName AS varchar(50)
SELECT @ColName = COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'MyTable'
AND COLUMN_NAME = @ColNameIn
IF @ColName IS NOT NULL
BEGIN
DECLARE @sql AS varchar(MAX)
SET @sql = REPLACE(@template, '{@ColName}', QUOTENAME(@ColName))
EXEC (@sql)
END
答案 2 :(得分:0)
阅读@SQLMenace答案中的链接!
declare @ColName varchar(50)
select @ColName = 'Column1'
declare @sql varchar(MAX)
select @sql = 'select ' + @ColName + ' MyTable where Column2 = 123'
exec (@sql)
答案 3 :(得分:0)
如果已在过程中预定义了所有可接受的列名,则可以使用CASE语句执行此操作。
DECLARE @ColName varchar(50)
SET @ColName = 'Column1'
SELECT CASE @ColName
WHEN 'Column1' THEN Column1
WHEN 'Column2' THEN Column2
END
FROM MyTable
WHERE Column2 = 123