我想删除“CASE ... WHEN ... END”语句并使用CTE或其他提示。 你有更好的方法吗?还是更好的要求?
SQL:
SELECT C.COLUMN_NAME
, DATA_TYPE
, CHARACTER_MAXIMUM_LENGTH
, IS_NULLABLE
, COLUMNPROPERTY(object_id(C.TABLE_SCHEMA+'.'+C.TABLE_NAME),
C.COLUMN_NAME, 'IsIdentity') AS IS_IDENTITY
, CASE I.IS_PRIMARY WHEN 1 THEN 1 ELSE 0 END AS IS_PRIMARY
, case I.IS_FOREIGN WHEN 1 THEN 1 ELSE 0 END AS IS_FOREIGN
FROM INFORMATION_SCHEMA.COLUMNS C
LEFT JOIN (
SELECT COLUMN_NAME
, OBJECTPROPERTY(OBJECT_ID(CONSTRAINT_SCHEMA + '.' +
QUOTENAME(CONSTRAINT_NAME)), 'IsPrimaryKey') AS IS_PRIMARY
, OBJECTPROPERTY(OBJECT_ID(CONSTRAINT_SCHEMA + '.' +
QUOTENAME(CONSTRAINT_NAME)), 'IsForeignKey') AS IS_FOREIGN
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE TABLE_NAME='MYTABLE'
) I ON C.COLUMN_NAME = I.COLUMN_NAME
WHERE C.TABLE_NAME='MYTABLE'
谢谢
答案 0 :(得分:3)
您可以使用ISNULL或COALESCE将NULL值设为默认值。这消除了您的CASE声明。
SELECT C.COLUMN_NAME
, DATA_TYPE
, CHARACTER_MAXIMUM_LENGTH
, IS_NULLABLE
, COLUMNPROPERTY(object_id(C.TABLE_SCHEMA+'.'+C.TABLE_NAME),
C.COLUMN_NAME, 'IsIdentity') AS IS_IDENTITY
, ISNULL(I.IS_PRIMARY,0) AS IS_PRIMARY
, ISNULL(I.IS_FOREIGN,0) AS IS_FOREIGN
FROM INFORMATION_SCHEMA.COLUMNS C
LEFT JOIN (
SELECT COLUMN_NAME
, OBJECTPROPERTY(OBJECT_ID(CONSTRAINT_SCHEMA + '.' +
QUOTENAME(CONSTRAINT_NAME)), 'IsPrimaryKey') AS IS_PRIMARY
, OBJECTPROPERTY(OBJECT_ID(CONSTRAINT_SCHEMA + '.' +
QUOTENAME(CONSTRAINT_NAME)), 'IsForeignKey') AS IS_FOREIGN
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE TABLE_NAME='MYTABLE'
) I ON C.COLUMN_NAME = I.COLUMN_NAME
答案 1 :(得分:1)
case
CASE I.IS_PRIMARY WHEN 1 THEN 1 ELSE 0 END
与
IIF(I.IS_PRIMARY = 1, 1, 0)
我相信它们的工作方式与我们关注的速度相同,但IIF()
更具人性化......
答案 2 :(得分:-2)
从我在这里看到的:
事实上,这些案件毫无用处。您可以删除
case ..... end
从两行开始