我想在存储过程中使用不同别名的查询字段
select COUNT(EmpCode) as CountEmp+@para
结果应该是
CountEmp1
CountEmp2
CountEmp1
c#代码中的查询循环:
select COUNT(EmpCode) where something = @something as CountEmp+@para
答案 0 :(得分:0)
请尝试使用以下代码。它与SQL Server 2012一起正常工作。
IF OBJECT_ID ('temp..#Mytable') IS NOT NULL
CREATE TABLE #Mytable (ID INT IDENTITY (1,1),EmpCode INT)
DECLARE @max int ,@count int
SET @max =0;
DECLARE @str varchar(10)
INSERT #Mytable
(EmpCode)
VALUES
(10),
(45),
(35),
(63),
(56),
(65)
SET @count = (SELECT COUNT (ID) FROM #Mytable )
WHILE @count > @max
BEGIN
SET @max = @max+1
SET @str = CONVERT(varchar(10),@max)
EXEC('SELECT EmpCode AS Empcode'+@str+ ' FROM #Mytable WHERE ID = '+@str)
END
答案 1 :(得分:0)
没有动态SQL的方法:
--I create temp table for demonstration
DECLARE @some_table TABLE (
Something int,
EmpCode INT
)
INSERT INTO @some_table (Something, EmpCode)
VALUES (1, 10),(1, 22),(1, 12),(2, 12),(2, 30),(3, 65),(3, 15),(3, 11),(3, 5)
--Declare parameter we want to search
DECLARE @param int = 1
--Query
--In cte we select what we need based on parameter
;WITH cte AS (
SELECT 'CountEmp'+CAST(@param as nvarchar(10)) as SomeThing,
CAST(COUNT(EmpCode) as nvarchar(10)) as EmpCodeCount,
ROW_NUMBER() OVER (ORDER BY SomeThing ) as rn
FROM @some_table
WHERE SomeThing = @param
GROUP BY SomeThing
)
--And here comes UNION
SELECT SomeThing as Result
FROM (
SELECT SomeThing,rn
FROM cte
UNION ALL
SELECT EmpCodeCount ,rn
FROM cte
) as t
ORDER BY rn, SomeThing DESC
输出:
Result
------------------
CountEmp1
3
(2 row(s) affected)