简体   繁体   English

我可以创建一个列名类似于另一个表的字段值的表,通过 SELECT 语句返回

[英]Can I create a table with columns named similar to field value of another table, return by SELECT statement

Question Image问题图片

When I execute this script, there is a syntax error.当我执行此脚本时,出现语法错误。 What is wrong with this?这有什么问题?

use TEST
go

CREATE TABLE newTagsTable 
( 
     (SELECT TEST.dbo.dynamicTags.Alais 
      FROM TEST.dbo.dynamicTags 
      WHERE ID = 2) varchar(200)
);

Is this what you need ?这是你需要的吗?

SELECT Alais 
into newTagsTable 
FROM dynamicTags 
WHERE ID = 2;

DEMO 演示

Ok, so something like this then:好的,那么像这样:

create procedure test_proc
as
declare @p_sql varchar(2000);
declare @p_sql_2 varchar(2000);
declare @getid CURSOR;

SET @getid = CURSOR FOR
SELECT Alais
FROM   dynamicTags;

begin
    set @p_sql = 'create table newTagsTable (';
    
    OPEN @getid
    FETCH NEXT
    FROM @getid INTO @p_sql_2
    WHILE @@FETCH_STATUS = 0
    begin
        set @p_sql = @p_sql + @p_sql_2 + ' varchar(20),'
        FETCH NEXT FROM @getid INTO @p_sql_2
    end;
    
    set @p_sql = left(@p_sql, len(@p_sql)-1) + ')';
    
    EXEC (@p_sql);
    
end;

And then just execute the procedure:然后只需执行程序:

exec test_proc

You can add parameters to this to make it more usable for orher situations... Here is the demo for this second option:您可以为此添加参数以使其更适用于其他情况......这是第二个选项的演示:

DEMO 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么我可以创建名为“key”和“value”的表列,但我以后不能使用它们? - Why I can create table columns named “key” and “value”, but I can't use them later? 如何从一个表中选择所有行,并根据另一表计算字段值 - How can I select all rows from one table, calculating a field value based on another table 从 Select 语句创建一个新列,然后在一个过程中将其与另一个 Select 语句组合以返回一个数据表 - Create a new column from Select statement then combining it with another Select statement in one procedure to return one data table 关于另一个表字段的Mysql Select语句 - Mysql Select Statement with respect to another table field 如何在select语句中为单独的列创建表 - How to create table for seperate columns in select statement 如何在 select 语句中对表列进行分组? - How can I group table columns in a select statement? 如何根据另一个字段的值在选择中返回一个值? - How can I return a value in a select based on the value of another field? 如何从两个相似的表中选择两个相似的字段? - How can I select two similar field from two similar table? 使用表中字段的值作为选择语句 - Use the value from a field in a table as a select statement 从另一个表中选择列并创建一个列 - select columns from another table and create a column
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM