在SQL中,如何在执行INSERT INTO SELECT时插入静态列值?

时间:2016-10-27 13:33:29

标签: sql sql-server

我需要编写一个SQL语句来复制行并将它们插入到同一个表中;但是,在其中一个字段中,我想为复制的每一行写一个静态值。我不知道该怎么做,但这是我到目前为止所做的:

INSERT INTO [xxx].[dbo].[TABLEX]
SELECT  [NAME]
  ,[DESC]
  ,[MODULE]
  ,[OWNER]  <=== I want all newly inserted rows to have "TERRY" as the owner
FROM [xxx].[dbo].[TABLEX]
WHERE OWNER = 'SAM' AND MODULE = 'ACC'

非常感谢你的帮助

4 个答案:

答案 0 :(得分:1)

INSERT INTO [xxx].[dbo].[TABLEX]
SELECT  [NAME]
  ,[DESC]
  ,[MODULE]
  ,'Terry'  <=== I want all newly inserted rows to have "TERRY" as the owner
FROM [xxx].[dbo].[TABLEX]
WHERE OWNER = 'SAM' AND MODULE = 'ACC'

答案 1 :(得分:1)

这可以完成工作 -

INSERT INTO [xxx].[dbo].[TABLEX]
SELECT  [NAME]
  ,[DESC]
  ,[MODULE]
  ,'Terry' AS [OWNER]  
FROM [xxx].[dbo].[TABLEX]
WHERE OWNER = 'SAM' AND MODULE = 'ACC'

答案 2 :(得分:1)

INSERT INTO [xxx].[dbo].[TABLEX]
SELECT  [NAME]
,[DESC]
,[MODULE]
,'TERRY'  
FROM [xxx].[dbo].[TABLEX]
WHERE OWNER = 'SAM' AND MODULE = 'ACC'

答案 3 :(得分:1)

[Owner]是否为字符串类型列,并且您想要填写&#39; TERRY&#39;从字面上看,试试这个:

INSERT INTO [xxx].[dbo].[TABLEX]
SELECT  [NAME]
  ,[DESC]
  ,[MODULE]
  ,'TERRY'
FROM [xxx].[dbo].[TABLEX]
WHERE OWNER = 'SAM' AND MODULE = 'ACC'

如果 - 我建议的话! - 所有者是另一个表的外键,并且您确定,Terry存在,您使用的是子选择:

INSERT INTO [xxx].[dbo].[TABLEX]
SELECT  [NAME]
  ,[DESC]
  ,[MODULE]
  ,(SELECT SomeID FROM SomeTable WHERE SomeColumn='TERRY')
FROM [xxx].[dbo].[TABLEX]
WHERE OWNER = 'SAM' AND MODULE = 'ACC'

但是你的WHERE - 条款让我想到,所有者是一个字符串列......

  • 你应该重新考虑这个设计