ruder

  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 :: 管理 ::
        public static void MakeSureExistTableAndColumns()
        {
            StringBuilder text = new StringBuilder();

            #region 如果表不存在
            text.AppendLine("if not  exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[" + CurrentType.Name + @"]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)");
            text.AppendLine("CREATE TABLE [dbo].[" + CurrentType.Name + @"] (");
            bool isFirst = true;
            foreach (PropertyInfo info in Attributes)
            {
                if (isFirst) { isFirst = false; } else { text.Append(","); text.AppendLine(); }
                object[] customerAttributes = info.GetCustomAttributes(true);
                string dbType = GetSqlType(info);
                bool IsPrimaryKey = false;
                if (customerAttributes != null)
                {
                    foreach (object obj in customerAttributes)
                    {
                        if (obj is TextAttribute && info.PropertyType.Name == "String")
                        {
                            dbType = ((TextAttribute)obj).SqlText;
                        }
                        else if (obj is IDAttribute)
                        {
                            IsPrimaryKey = true;
                        }
                    }
                }
                text.Append(" [" + info.Name + "] " + dbType);
                if (info.PropertyType.ToString() == "String")
                {
                    text.Append(" COLLATE Chinese_Taiwan_Stroke_CI_AS " +( IsPrimaryKey?" Not ":"") + " NULL ");
                }
            }
            text.AppendLine("  ) ON [PRIMARY]");
            #endregion
posted on 2009-04-29 17:43  徐境  阅读(160)  评论(0)    收藏  举报