0

I am using SQL Server 2012. I am new to T-SQL.

I have a table called tblEmp where phone no of some employee is NULL.

I want to copy all these data to a new table using INTO clause, but in the new table it should replace all the NULL phone nos with a string 'NA'

I think this can be done by CASE statement.

4

4 回答 4

4

您可以使用ISNULL语句

询问:

INSERT INTO table_name (column1,column2,column3,...)
SELECT isnull(phone_no, 'NA')  AS phone_no,
       name,
       .....
FROM tblEmp

SELECT-INTO 语句

SELECT isnull(phone_no, 'NA') AS phone_no,
       name,
       .....
INTO newtable
FROM tblEmp

ExampleSqlFiddle

于 2013-09-14T08:24:05.990 回答
3
INSERT INTO NewTable(col1,col2,....)
SELECT case when phone_no is null then 'NA' else phone_no end,
   name,....
FROM tblEmp
于 2013-09-14T08:34:32.110 回答
0

稍微简单一点(无需显式声明所有列名),但分两步:

select * into newTable from tblEmp
update newTable set phoneNo = 'NA' where phoneNo is null

可能不是你想要的。

于 2013-09-14T08:58:50.793 回答
0

使用 COALESCE ( http://sqlzoo.net/wiki/COALESCE )。

COALESCE 接受任意数量的参数并返回第一个非空值。COALESCE(x,y,z) = x 如果 x 不为 NULL COALESCE(x,y,z) = y 如果 x 为 NULL 并且 y 不为 NULL COALESCE(x,y,z) = z 如果 x 和 y 为 NULL但 z 不为 NULL

INSERT INTO tblEmp2(Column1, Column2, ...)
SELECT (COALESCE(tblEmp.phone, 'NA'), ...)
FROM tblEmp
于 2013-09-14T10:59:04.583 回答