简体   繁体   English

将具有NULL值的列添加到临时表

[英]Adding column with NULL values to temp table

I am trying to create a temp table with values from an existing table. 我试图用现有表中的值创建一个临时表。 I would like the temp table to have an additional column (phone), which does not exist from the permanent table. 我希望临时表具有一个附加列(电话),该列在永久表中不存在。 All values in this column should be NULL. 此列中的所有值都应为NULL。 Not sure how to do, but here is my existing query: 不确定该怎么做,但这是我现有的查询:

SELECT DISTINCT UserName, FirstName, LastName INTO ##TempTable 
FROM (
      SELECT DISTINCT Username, FirstName, LastName 
          FROM PermanentTable
)  data 

You need to give the column a value, but you don't need a subquery: 您需要为该列提供一个值,但不需要子查询:

SELECT DISTINCT UserName, FirstName, LastName, NULL as phone
INTO ##TempTable 
FROM PermanentTable;

In SQL Server, the default type for NULL is an int. 在SQL Server中, NULL的默认类型是int。 It is more reasonable to store a phone number as a string, so this is perhaps better: 将电话号码存储为字符串更为合理,因此这可能更好:

SELECT DISTINCT UserName, FirstName, LastName,
       CAST(NULL as VARCHAR(255)) as phone
INTO ##TempTable 
FROM PermanentTable;

Just add the name of column that you will insert into TempTable and in inner select just select NULL 只需添加将插入到TempTable中的列的名称,然后在内部选择仅选择NULL

something like this 像这样的东西

SELECT DISTINCT UserName, FirstName, LastName, Phone INTO ##TempTable 
FROM (
  SELECT DISTINCT Username, FirstName, LastName, NULL
      FROM PermanentTable
 )  data 

Rewrite the query as - 将查询重写为-

CREATE TABLE ##TempTable(UserName datatype, FirstName datatype, LastName datatype,Phone datatype)
INSERT INTO INTO ##TempTable (UserName, FirstName, LastName,Phone )
SELECT DISTINCT UserName, FirstName, LastName,NULL 
FROM (
      SELECT DISTINCT Username, FirstName, LastName 
          FROM PermanentTable
)  data 

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

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