2014-12-02 304 views
2

我似乎無法得到適合我的嵌套if的格式。基本上我試圖做的是運行嵌套的IF語句SQL

select columnproperty(object_id(@TableName),t.name,'IsIdentity') = 0 

針對下面創建的循環。如果它是一個Idendity科拉姆,我不希望它加入

DECLARE @TableName VARCHAR(50) 
SELECT @TableName ='Users' 
select -1 as colid, 'public class obj_' + @TableName + '{' 
union 

SELECT c.colid, 
      'public '+ 
       (CASE WHEN t.name IN ('int', 'bigint') THEN 'Int32?' 
        WHEN t.name IN ('nvarchar','varchar','text','ntext') THEN 'String' 
        WHEN t.name IN ('datetime','smalldatetime') THEN 'DateTime?' 
        WHEN t.name IN ('decimal') THEN 'Decimal?' 
        WHEN t.name IN ('bit') THEN 'Boolean?' 
        ELSE 'Unknown' 
       END) + ' ' + c.name + '{ get; set; }' 
     FROM syscolumns c JOIN 
      systypes t 
      ON t.xusertype=c.xusertype 
     WHERE id IN (SELECT id FROM sysobjects WHERE name = @TableName) 
      union 
      select 1000 as colid, '}' 

回答

1

使用sys意見,濾波器sys.columns.is_identity

SELECT c.column_id, 
     'public '+ 
      (CASE WHEN t.name IN ('int', 'bigint') THEN 'Int32?' 
       WHEN t.name IN ('nvarchar','varchar','text','ntext') THEN 'String' 
       WHEN t.name IN ('datetime','smalldatetime') THEN 'DateTime?' 
       WHEN t.name IN ('decimal') THEN 'Decimal?' 
       WHEN t.name IN ('bit') THEN 'Boolean?' 
       ELSE 'Unknown' 
      END) + ' ' + c.name + '{ get; set; }' 
    FROM  
     sys.columns c 
    INNER JOIN 
     sys.types t ON c.user_type_id = t.user_type_id 
    WHERE 
     c.object_id = OBJECT_ID(@TableName) 
    AND 
     c.is_identity = 0 
    UNION 
     select 1000 as colid, '}' 
+0

啊,太感謝你了。這很有道理 – TMB87 2014-12-02 13:18:31