[英]Can I create a table with columns named similar to field value of another table, return by SELECT statement
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;
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:您可以为此添加参数以使其更适用于其他情况......这是第二个选项的演示:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.