使用SQL Server SELECT INTO创建不可为空的列

时间:2018-06-18 09:33:36

标签: sql-server

RTRIM和LTRIM使列可以为空。我怎么能让它们不可空?

CREATE TABLE SO_IN
(
    RAW NVARCHAR(10) NOT NULL
) ;
GO

SELECT
    RAW,
    RTRIM(RAW) AS RTRIM,
    LTRIM(RAW) AS LTRIM
INTO SO_OUT
FROM
    SO_IN;

SELECT COLUMN_NAME, IS_NULLABLE
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_NAME = 'SO_OUT'

输出将是:

COLUMN_NAME|IS_NULLABLE
-----------|-----------
RAW        |NO
RTRIM      |YES
LTRIM      |YES

我希望他们都是IS_NULLABLE NO

2 个答案:

答案 0 :(得分:1)

这比我想的更简单:

CREATE TABLE SO_IN
(
    RAW NVARCHAR(10) NOT NULL
) ;
GO

SELECT
    RAW,
    ISNULL(RTRIM(RAW),'') AS RTRIM,
    LTRIM(RAW) AS LTRIM
INTO SO_OUT
FROM
    SO_IN;

SELECT COLUMN_NAME, IS_NULLABLE
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_NAME = 'SO_OUT'

答案 1 :(得分:1)

您必须应用ISNULL才能将其作为SELECT * INTO的非可空字段。

CREATE TABLE SO_IN
(
    RAW NVARCHAR(10) NOT NULL
) ;
GO

SELECT
    RAW,
    ISNULL(RTRIM(RAW),'') AS RTRIM,
    ISNULL(LTRIM(RAW),'') AS LTRIM
INTO SO_OUT
FROM
    SO_IN;

SELECT COLUMN_NAME, IS_NULLABLE
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_NAME = 'SO_OUT'