【问题标题】:dynamic alias in sql serversql server 中的动态别名
【发布时间】:2016-05-25 07:44:12
【问题描述】:

我想要存储过程中具有不同别名的查询字段

select COUNT(EmpCode) as  CountEmp+@para

结果应该是

CountEmp1

45

CountEmp2

54

CountEmp1

76

C#代码中的查询循环:

select COUNT(EmpCode) where something = @something as CountEmp+@para 

【问题讨论】:

  • 您面临什么问题?也添加代码
  • 你不能做动态别名(除非你使用动态 SQL)。这样做的目的是什么?
  • 你想动态传递不同的表名吗?
  • 无论别名是什么,您都无法通过重命名获得不同的值。请显示所有产生这些值的查询文本。
  • 我通过匹配主键循环填充查询结果在 c# 数据表中,但如果每次列名相同,如 [empcode] 数据表在每次迭代时覆盖查询结果,所以想通过 c# 传递参数来更改别名名称不同的列名

标签: sql sql-server database stored-procedures


【解决方案1】:

没有动态 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)

【讨论】:

    【解决方案2】:

    请尝试使用以下代码。它在 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
    

    【讨论】:

      猜你喜欢
      • 2023-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-09
      • 1970-01-01
      • 1970-01-01
      • 2020-06-10
      相关资源
      最近更新 更多