嵌套的IF语句SQL

时间:2014-12-02 13:00:14

标签: sql sql-server

我似乎无法为我的嵌套if获得正确的格式。基本上我要做的就是运行

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

针对下面创建的循环。如果它是Idendity colum,我不想要它添加

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 个答案:

答案 0 :(得分: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, '}'