简体   繁体   English

T-SQL复制现有列信息

[英]T-SQL Copy existing Column information

I'm currently creating a SP that will copy information from table a into table b. 我当前正在创建一个SP,它将信息从表a复制到表b。 The problem that I'm facing is that the information that will be copied can be freely defined in table c. 我面临的问题是可以在表c中自由定义要复制的信息。 So for Example: Table a has the columns test nvarchar(50), test1 nvarchar(79), beta2 nvarchar(80) and id int 因此,例如:表a具有列test nvarchar(50),test1 nvarchar(79),beta2 nvarchar(80)和id int

In the settings table it is defined that the columns test and test1 should be copied from table a to table b. 在设置表中,定义了将test和test1列从表a复制到表b。

I did include a check if the column already exists. 我确实检查了该列是否已经存在。 It now fails at the following lines: 现在,它在以下几行失败:

DECLARE @dataType nvarchar(100)
DECLARE @statement nvarchar(250)

set @dataType = 
SELECT c.*, s.name 
FROM sys.columns c 
INNER JOIN sys.objects o 
ON c.object_id = o.object_id 
INNER JOIN sys.types s 
ON c.user_type_id = s.user_type_id 
WHERE o.name = 'a' AND c.name = 'test'
set @Statement = 'Alter table dbo.t_hist_Devicereport add test ' + @dataType 
exec (@Statement)

The Error message is that I've incorrect syntax near SELECT but if I run the SELECT statement by itself it works quite fine... I'm using SQL Server 2005 in case that could be a problem 错误消息是我在SELECT附近语法不正确,但是如果我自己运行SELECT语句,它就可以正常工作...我正在使用SQL Server 2005,以防出现问题

DECLARE @dataType nvarchar(100)
DECLARE @statement nvarchar(250)
SELECT @dataType = CASE WHEN s.name = 'nvarchar' THEN 'nvarchar(' + CAST(c.max_length AS varchar(4)) + ')' ELSE s.name END             
FROM sys.tables t JOIN sys.columns c ON t.object_id = c.object_id 
                  JOIN sys.types s ON c.user_type_id = s.user_type_id 
WHERE t.name = 'a' AND c.name = 'test'

SET @Statement = 'Alter table dbo.t_hist_Devicereport add test ' + @dataType 
EXEC sp_executesql @Statement

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM