SQL Server中的IF子句或CASE语句

时间:2011-06-27 19:25:11

标签: sql-server if-statement case

我如何做以下代码:

 SELECT c.TABLE_NAME, c.COLUMN_NAME, c.DATA_TYPE, c.Column_default, c.character_maximum_length, c.numeric_precision, c.is_nullable,
 if(u.CONSTRAINT_TYPE = 'PRIMARY KEY')
 Begin
print 'primary key'
 end
else
begin
print ''
end
 FROM INFORMATION_SCHEMA.COLUMNS as c
 LEFT OUTER JOIN information_schema.CONSTRAINT_table_USAGE as u
 ON c.table_name = u.table_name
 Order by table_name

2 个答案:

答案 0 :(得分:2)

SELECT
    c.TABLE_NAME, c.COLUMN_NAME, c.DATA_TYPE, c.Column_default,
    c.character_maximum_length, c.numeric_precision, c.is_nullable,
    case
     when u.CONSTRAINT_TYPE = 'PRIMARY KEY' then 'primary key'
     else ''
    end as pk
 FROM INFORMATION_SCHEMA.COLUMNS as c
 LEFT OUTER JOIN information_schema.CONSTRAINT_table_USAGE as u
 ON c.table_name = u.table_name
 Order by table_name

您无法在SELECT课程中打印

答案 1 :(得分:1)

试试这个:

 SELECT ..., c.is_nullable,
        CASE WHEN u.CONSTRAINT_TYPE = 'PRIMARY KEY' THEN 'primary key'
        ELSE '' 
        END AS KeyType
FROM INFORMATION_SCHEMA.COLUMNS as c