sql - 使用多个列中的数据填充单个 SQL Server 列并向值添加前缀

标签 sql sql-insert

更新我最终只是在插入值之前使用了插入并将其分配给 p_id = 0,结果就是我需要的那样。谢谢!

INSERT INTO table2 (p_id,value)
Values(0,@@SYS=DEV');

我尝试合并 Table1 中的 3 列,并将 Table2 中的值放在单个列中,但我还想在这些值前加上 A、& B 和 C 前缀,如下所示。 P_Id 自动递增。

表1

+---------+--------+-----------+
| Emp_ID  | Status | hire_date | 
+---------+--------+-----------+
| 12345   | happy  | 10/10/2005|
| 54321   | sad    | 12/01/2009|
+---------+--------+-----------+

插入表2...

我以为我可以在此解决方案中插入一条静态行,但它在每个新的 emp_id 上重复,而我只需要在顶行中使用一次。

+------+--------------+
| P_Id |    Info      | 
+---------------------+
| 1    | @@=Dev       |
| 2    | A,12345      |
| 3    | B,happy      |
| 4    | C,10/10/2005 | 
| 5    | A,54321      |
| 6    | B,sad        |
| 7    | C,12/01/2009 |
+------+--------------+

非常感谢任何帮助!环境为SQL Server 2008。

最佳答案

您可以通过一次选择来完成此操作,如下所示:

with cte as (
    select T.Emp_ID, C.Value
    from Table1 as T
        outer apply (values
            ('A,' + cast(T.Emp_ID as varchar(max))),
            ('B,' + T.Status),
            ('C,' + convert(varchar(10), T.hire_date, 103))
        ) as C(Value)
)
-- insert into Table2
select
    row_number() over(order by Emp_ID, Value) as p_id,
    Value
from cte

sql fiddle demo

关于sql - 使用多个列中的数据填充单个 SQL Server 列并向值添加前缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19550234/

相关文章:

postgresql - 在带有 SELECT 语句的 INSERT INTO 语句中返回

mysql - 如何将不同的查询答案插入到表中

mysql - 将值插入表中的新列,根据同一表中的数据计算

Postgresql 不截断超长字符串

javascript - 使用 HTML/PHP/AJAX 将行插入数据库

sql - rails : mixing NOSQL & SQL Databases

sql - 在sql中使用Oracle "at time zone"函数 - 问题及解决方案

sql - 在 BigQuery 中将行转置为列(Pivot 实现)

mysql - 如何在 Groovy 中收集 sql 行

MySQL - 根据最新日期和每列的 id 列表将行转换为列