我尝试使用SQL构建一类对象,以便将来在我的应用中使用。基本上你通过表名传递它,它会返回你要粘贴到c#的类的语法
它适用于某一点,但有些项目以奇怪的顺序返回:
DECLARE @TableName VARCHAR(50)
SELECT @TableName ='Users'
select 'public class obj_' + @TableName + '{'
union
SELECT '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 as c
JOIN systypes t ON t.xusertype=c.xusertype
WHERE id IN (SELECT id FROM sysobjects WHERE name=@TableName)
union
Select '}'
它返回它:
}
public Boolean IsAdmin{ get; set; }
public class obj_Users{
public Int32 UserCompanyID{ get; set; }
public Int32 UserID{ get; set; }
public Int32 UserRole{ get; set; }
public String Email{ get; set; }
public String FirstName{ get; set; }
public String SessionKey{ get; set; }
public String Surname{ get; set; }
public String UserName{ get; set; }
public String UserPassword{ get; set; }
答案 0 :(得分:0)
尝试按colid
排序。鉴于您的查询,这有点挑战,但这可能会有效:
select 'public class obj_' + @TableName + '{'
union all
(SELECT '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 as c
JOIN systypes t
ON t.xusertype=c.xusertype
WHERE id IN (SELECT id FROM sysobjects WHERE name=@TableName)
ORDER BY colid)
union all
Select '}'
更强大的解决方案是使用子查询:
select str
from ((select -1 as ordering, 'public class obj_' + @TableName + '{' as str
union all
(SELECT 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 all
(Select 10000, '}')
)
ORDER BY ordering