摘要: 一直有查wiki的习惯,最近发现好多查了了后又不太记得,然后又查的时候发现已经查过了。(尴尬,记性不太好)有些东西一时难以完全掌握,所以今后凡是看过的都记录下来,方便第二次学习。小端序:http://zh.wikipedia.org/zh-cn/%E5%B0%8F%E7%AB%AF%E5%BA%8F#.E5.B0.8F.E7.AB.AF.E5.BA.8FASCII:http://zh.wikipedia.org/zh-cn/Ascii观察者模式:http://zh.wikipedia.org/wiki/%E8%A7%82%E5%AF%9F%E8%80%85%E6%A8%A1%E5%BC%8Fl阅读全文
posted @ 2010-01-03 10:26 冰の酷龙 阅读(69) 评论(0) 编辑

   这几天因为CSDN明文密码泄露的事情闹得沸沸扬扬.在年关将至的时候火了一把.让我想起我们项目中的会员密码是如何保存的?

   这部分代码是之前曹哥或张博士所留,平常虽然有看过,但也没有仔细研究,只记得有HASH有Salt(盐?).但到底如何实现,今天就当作复习了一下.

   思路以前有所了解,首先产生一个5位数的Salt,然后将password和salt进行Hash.但是具体代码的实现,确实没有了解.

 

产生Salt:

        /// <summary>
        /// 产生随机的混入字符串
        /// </summary>
        /// <param name="length">产生的字符串的长度</param>
        /// <returns>随机字符串</returns>
        public static string CreateSalt(int length)
        {
            Random r = new Random();
            StringBuilder sb = new StringBuilder(length);
            for (int i = 0; i < length; i++)
            {
                sb.Append(constant[r.Next(constant.Length)]);
            }
            return sb.ToString();
        }

 在salt产生中使用了一个constant的数组:

  private static char[] constant ={'0','1','2','3','4','5','6','7','8','9',
        'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r',
        's','t','u','v','w','x','y','z',
        'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R',
        'S','T','U','V','W','X','Y','Z' };

 将password和salt混入并Hash:

 /// <summary>
        /// 混入并计算Hash值
        /// </summary>
        /// <param name="rawString">原始字符串</param>
        /// <param name="salt">混入字符串</param>
        /// <returns>混入后字符串的Hash值</returns>
        public static string SaltAndHash(string rawString, string salt)
        {
            string plan = string.Concat(rawString, salt);
            return plan.Hash();
        }

 hash算法:

  /// <summary>
        /// 计算字符串的Hash值
        /// </summary>
        /// <param name="planText">明文</param>
        /// <returns>Hash值</returns>
        public static string Hash(this string planText)
        {
            byte[] plan = Encoding.UTF8.GetBytes(planText);

            SHA256 hasher = new SHA256Managed();
            byte[] hashed = hasher.ComputeHash(plan);

            return Convert.ToBase64String(hashed);
        }
posted @ 2012-01-11 17:15 冰の酷龙 阅读(11) 评论(0) 编辑

   这次用JSCharts做报表,发现对于生成报表参数很是恼火,它有两种参数:

   一是Line:var myData = new Array([10, 20], [15, 10], [20, 30], [25, 10], [30, 5]);

   二是Bar:var myData = new Array(['unit', 20], ['unit two', 10], ['unit three', 30], ['other unit', 10], ['last unit', 30]);

   如何将Controller中获得的数据生成JavaScript的数组呢?

   一种是toJson的方法:

 

        public static string ToJSON(this object obj)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(obj);
}

public static string ToJSON(object obj, int recursionDepth)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.RecursionLimit = recursionDepth;
return serializer.Serialize(obj);
}
 var data=new Array();
$(document).ready(function(){
var content=<%=ViewData["Schedules"]==null?0:ViewData["Schedules"] %>;
if(content!=0)
{
$.each(content, function(i, item) {
data.push(new Array(item["ItemA"],item["ItemB"],item["ItemC"]));
});
}
});

   参考:http://www.soaspx.com/dotnet/asp.net/DPattern/dpattern_20091104_1419.html
   

另一种是foreach ViewData,我选的这种:

  

public class Address
{
public string Line1 { get; set; }
public string City { get; set; }
}

// in your controller code
ViewData["Addresses"] = new List<Address>(new Address[] { new Address() { Line1="bla", City="somewhere"}, new Address() {Line1="foo", City="somewhereelse"}});

   前台:

<script type="text/javascript">
var addresses = new Array(
<% for (int i = 0; i < ViewData["Addresses"].Count; i++) { %>
<%= i > 0 : "," : "" %>({line1:"<%= addr.Line1 %>", city:"<%= addr.City %>"})
<% } %>);
</script>  

还可以这样:

var cityList = new Array();
function addCity(cityId, cityName) {
var city = new Object();
city.CityID = cityId;
city.CityName = cityName

cityList .push(city);
}
<% foreach (Something.DB.City item in ViewData["Cities"] as List<City>)
{ %>
addCity(item.Id, item.Name);
<% } %>

   有几点需要注意,我的代码如下:

  var callin = new Array();
function addReport( callin, callout) {
var data = new Array(callin, callout);
array.push(data);
}
'<%foreach(var item in ViewData["reports"] as List<CDRDayReport>){ %>'
addReport('<%=item.CallIn %>','<%=item.CallOut %>'); //string
//addReport(<%=item.CallIn %>,<%=item.CallOut %>); //number
'<%} %>'

   PS:JSCharts的需要的参数,是数组嵌套数组。开始我一直没弄明白怎么生成这样的数据,其实很简单:

 var array = new Array();
var data = new Array(10, 2);
var data2 = new Array(12, 3);
array.push(data);
array.push(data2);

   唯一需要注意的是,如果只有1个data,JSCharts会报错,因为一个点生成不了line嘛,后来才想通。






 

 

posted @ 2012-01-11 09:59 冰の酷龙 阅读(6) 评论(0) 编辑

   有一个很简单的需求,我想把自己的微博的内容输出到我的网站上。本以为是个很简单的事情,结果折腾了一晚上。

   首先想到使用新浪微博,因为平常自己用的就是新浪微博。网上有很多关于新浪微博的API开发,首先就找到了dudu站长的分享:http://www.cnblogs.com/cmt/archive/2010/05/13/1733904.html 第一步是要申请账号:http://open.weibo.com/  现在申请已经不需要发邮件了。非常简单,申请成为开发者,然后创建应用,填写正确的邮箱地址,马上就收到App Key了。

    拿到这个Key后,没有照dudu的代码试一遍,因为其介绍的是发布内容到微博,而我的要求是获取微博内容到网站。 文章下面推荐使用:http://code.google.com/p/opensinaapi/ ,下载之后便可以直接使用了。里面有个示例代码,修改web.config中的appkey后可以直接运行。

点击连接按钮后,弹出窗口,需要授权。

授权完成后,即可调用相关方法,返回也没有问题,可以成功输出。

本以为皆大欢喜,但总觉得哪里不对,是“授权”!每次登录都会弹出这该死的授权页面。

尝试按照dudu文章里面的代码,结果总是报错:

反复查找新浪的开发指南,始终没找到方法,又去了开发者论坛找:http://forum.open.weibo.com/ 有与我碰到同样问题的朋友,不过也没有解决办法。

不过得到几个关键信息:

1.使用oAuth是一定会弹出授权页面的。

2.basic登录已经不开放了。

3.oauth2.0授权有效期是24小时。

4.用户名密码方式需要申请。

几个有用的帖子:http://forum.open.weibo.com/read.php?tid=14795&fpage=4&page=1 

                      http://forum.open.weibo.com/read.php?tid=6715

                      http://forum.open.weibo.com/read.php?tid=8036

实在想不到什么好办法了,只好继续搜索。

beer提供了一种方法获取RSS:http://www.cnblogs.com/beer/archive/2010/05/17/1737679.html  不过这个方法我没有试。

 

新浪的路看来是走不通了,抱着侥幸的心理试试腾讯的微博。

类似的方法进行开发者申请,同样是创建应用后通过邮件收到appKey.阅读开发文档的时候有个让我眼前一亮的东东:RSS/JSONP输出。

https://open.t.qq.com/resource.php?i=3,3

需要登录访问,可以直接获取两种方式的调用地址:

如我的:http://v.t.qq.com/output/json.php?type=2&name=dragonice&sign=fa46dfdc668d42faf78b11193ea12db7ec207678 

直接输入浏览器中即可出现jsonp的数据(要多刷新几次)。这不正是我想要的东东吗?本以为万事大吉,想通过jquery的getJSON()轻松获取:

  $.getJSON("http://v.t.qq.com/output/json.php", { type: "2", name: "dragonice", sign: "fa46dfdc668d42faf78b11193ea12db7ec207678" },
            function (db) {
            var msg = "";
            for (var i = 0; i < db.data.length; i++) {
            msg += "<p>" + db.data[i].content + "</p>";
            }
            document.getElementById('weibo').innerHTML = msg;
            }
            ); 

结果死活得不到数据。不甘心,可能是json和jsonp不同,找到一篇文章:http://www.cnblogs.com/cfanseal/archive/2009/05/19/1460382.html通过ajax()来尝试:

 $.ajax({
                url: "http://v.t.qq.com/output/json.php?type=2&name=dragonice&sign=fa46dfdc668d42faf78b11193ea12db7ec207678",
                type: "GET",
                dataType: "JSONP",
                success: function (db) {
                    alert("a");
                    var msg = "";
                    for (var i = 0; i < db.data.length; i++) {
                        msg += "<p>" + db.data[i].content + "</p>";
                    }
                    document.getElementById('weibo').innerHTML = msg;
                }
            });

没有成功(有时会报weiboData()没有定义的错误。)。反反复复试了N次,还是不成功。装个chrome浏览器(chrome确实比ie9快,MS怎么这么不给力啊!)。调试后发现数据得到了,但是处理不正确。整了N久还是不行。本来想放弃算了,还是求助了下Google,结果发现了这个:http://wiki.xnwww.net/front/%E9%80%9A%E8%BF%87%E8%A7%A3%E6%9E%90jsonp%E6%A0%BC%E5%BC%8F%E8%BE%93%E5%87%BA%E8%85%BE%E8%AE%AF%E5%BE%AE%E8%96%84

<div id="weibo"> 微薄正在加载中</div>
		<script type="text/javascript" src="jquery.min.js"></script>
         <script type="text/javascript">
             function weiboData(db){
                                var msg="";
                                for(var i=0;i<db.data.length;i++){
                                    msg+="<p>"+db.data[i].content+"</p>";    
                                }
                                document.getElementById('weibo').innerHTML=msg;
                                   }
 
		</script>
        <script type="text/javascript" src="http://v.t.qq.com/output/json.php?type=1&name=noecnet&sign=d761e44f9240993f8176ed38088ed224c6fd71bc"></script>

一段代码就搞定了。

其实有种方法一直想试,但是没js调用没成功,怎么都不甘心。尝试一下发现是可以的:

string url = "http://v.t.qq.com/output/json.php?type=2&name=dragonice&sign=fa46dfdc668d42faf78b11193ea12db7ec207678";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.ContentType = "application/x-www-form-urlencoded";

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("UTF-8"));
            string retString = myStreamReader.ReadToEnd();

            Response.Write(retString);

  

posted @ 2011-12-13 01:20 冰の酷龙 阅读(57) 评论(0) 编辑

    
 SQL Server编程必知必会
                           ----读书笔记
介绍:
sp_databases;返回可用数据的一个列表.
sp_tables;返回当前所选数据库内可用表的列表.包含了系统表.
sp_tables null,dbo,hcrs,"'TABLE'";获得表的列表,不包括视图,也不包括系统表.
sp_columns table;用来显示表列,要求指定表名.
sp_server_info;用来显示服务器状态信息.
sp_spaceused;用来显示数据库使用(和未使用)的空间量.
sp_statistics table;用来显示与数据库有关的使用统计数据.
sp_helpuser;用来显示可用的用户账号.
sp_helplogins;用来显示用户登录及它们具有的权限.
 
数据类型
字符串类型:
char     1~8000个字符的定长字符串
nchar   1~4000个字符的定长Unicode字符串
ntext     变长Unicode文本
nvarchar   变长Unicode文本
text       变长文本
varchar 变长文本
 
数值类型:
bit    单个二进制位字段
bgint 整数值
decimal 精度可变的浮点值
float  变长字节浮点
int   整数类型
money  精确到小数点后4位的货币值
real    4字节浮点值
smallint   整数值(-32768~32767)
tinyint   整数值(0~255)
 
日期和时间类型
datetime    1753.1.1~9999.12.31
smalldatetime  1900.1.1~2079.6.6
 
二进制数据类型
binary   定长二进制数据,最多8000个字符
varbinary  变长二进制数据,最多8000个字符
varbinary(max)  变长二进制数据,超过8000个字符
 
 
 
检索:
DISTINCT
select distinct vend_id from products; 指定返回不同的值.
PS:distinct应用于所有的列(所有列相同才排除),如select distinct vend_id,prod_price from products,将返回所有的行.
TOP
select top(5) prod_name from products;top(5)指定最多返回5行.
PS:top超过最大行,即取最大行数.
PERCENT
select top(25) percent prod_name from products;联合top来获得行的百分比.
PS:14行取4行,超出即算1行.
TABLESAMPLE
select * from products tablesample(3 rows); 检索任意3行(但实际不是)
select * from products tablesample(50 percent);检索50%的行(实际也不是)
PS:采样由表分页产生(SQL Server使用的内部机制实际上是存储数据),且一页上的行数可以变化.
 
排序
按多个列排序,只要指定列明,列明之间用逗号分开即可.
select prod_id,prod_price,prod_name from products order by prod_price,prod_name;
PS:仅在多个行具有相同的prod_price值时才对产品按prod_name进行排序.
DSSC 降序排序
ASC 升序排序
PS:select top(1) prod_price from products order by prod_price desc;  找到最大值.
        select top(1) prod_price from products order by prod_price;找到最小值
 
过滤数据
where 子句操作符
= 等于
<> 不等于
!= 不等于
< 小于
<= 小于等于
!< 不小于
> 大于
>= 大于等于
!> 不大于
between 在指定的两个值之间
is null 为null值
 
BETWEEN
select prod_name,prod_price from products where prod_price between 5 and 10;
将匹配范围中所有的值,包括指定的开始值和结束值.
 
NULL 无值(no value),与字段包含0、空字符串或仅包含空格不同.
select prod_name from products where prod_price is null.空值检测
 
数据过滤
select prod_name,prod_price
from products
where (vend_id=1002 or vend_id=1003) and prod_price>=10
结果中会出现价格小于10的数据.原因在于,t-sql在处理or操作符前,优先处理and操作符.可以用圆括号进行分组.
 
IN 用来指定条件范围,范围中的每个条件都可以进行匹配.
select prod_name,prod_price from products  where vend_id in(1002,1003)
order by prod_name
PS:in 与 or 类似,但更具优势
1.in操作语法更加清楚直观;2.in操作计算次序更容易管理;3.in操作符一般比or操作符执行更快;4.in可以包含其他select语句;
 
NOT 否定它之后所跟的任何条件
select prod_name,prod_price from prducts
where vend_id not in(1002,1003)
order by prod_name
 
LIKE 利用通配符匹配
百分号(%)通配符:出现任意次数的任何字符。%不匹配null。
下划线(_)通配符:匹配单个字符而不是多个字符。
方括号([ ])通配符:指定一个字符集,它必须匹配指定位置(通配符的位置)的一个字符。
                              select cust_contact from customers where cust_contact like '[EJ]%' order by cust_contact; //找出e或j起头的联系人
可以使用脱字符(^)来否定。
 
计算字段
+  操作符拼接两个列
select vend_name + ' (' + vend_country +')' from vendors order by vend_name
select Rtrim(vend_name) + ' (' + Rtrim(vend_country) +')' from vendors order by vend_name
RTrim() 函数,删除右侧多余空格。
LTrime()函数,删除左边多余空格。
 
as 别名
select Rtrim(vend_name) + ' (' + Rtrim(vend_country) +')' as vendors from vendors order by vend_name

函数
字符串处理
Upper() 全大写
CharIndex() 返回字符串指定字符的位置
Left() 返回字符串左边的字符
Len() 返回字符串的长度
Lower() 将字符串转换为小写
LTrim() 去掉字符串左边的空格
Replace() 其他特殊字符替换字符串中的字符
Right() 返回字符串右边的字符
Rtrim() 去掉字符串右边空格
Soundex() 返回字符串的SOUNDEX值
str() 将数值转换为字符串
SubString() 返回字符串中的字符
Upper() 将字符串转换为大写
 
select cust_name,cust_contact from Customers where Soundex(cust_contact)=Soundex('Y Lie');
发音相似的单词其Soundex值匹配。
 
时间处理
DateAdd() 添加日期
DateDiff() 计算两个日期的差
DateName() 返回部分日期的字符串表示
DatePart() 返回日期的一部分(星期几、月、年等)
Day() 返回日期中的天
GetDate() 返回当前日期和时间
Month() 返回日期中的月
Year() 返回日期中的年
 
缩写
天 dd或d
年中的天 dy或y
时 hh
毫秒  ms
分 mi或n
月份  m或mm
季度 q或qq
秒  ss或s
周 wk或ww
周中的天  dw
年  yy或yyyy
 
附表:
select CONVERT(varchar, getdate(), 120 )
 2004-09-12 11:06:08
 select replace(replace(replace(CONVERT(varchar, getdate(), 120 ),'-',''),' ',''),':','')
 20040912110608

 
 select CONVERT(varchar(12) , getdate(), 111 )
 2004/09/12

 
 select CONVERT(varchar(12) , getdate(), 112 )
 20040912

 
 select CONVERT(varchar(12) , getdate(), 102 )
 2004.09.12

 
 其它我不常用的日期格式转换方法:

 
 select CONVERT(varchar(12) , getdate(), 101 )
 09/12/2004

 
 select CONVERT(varchar(12) , getdate(), 103 )
 12/09/2004

 
 select CONVERT(varchar(12) , getdate(), 104 )
 12.09.2004

 
 select CONVERT(varchar(12) , getdate(), 105 )
 12-09-2004

 
 select CONVERT(varchar(12) , getdate(), 106 )
 12 09 2004

 
 select CONVERT(varchar(12) , getdate(), 107 )
 09 12, 2004

 
 select CONVERT(varchar(12) , getdate(), 108 )
 11:06:08

 
 select CONVERT(varchar(12) , getdate(), 109 )
 09 12 2004 1

 
 select CONVERT(varchar(12) , getdate(), 110 )
 09-12-2004

 
 select CONVERT(varchar(12) , getdate(), 113 )
 12 09 2004 1

 
 select CONVERT(varchar(12) , getdate(), 114 )
 11:06:08.177

 
select order_num,DATEPART(weekday,order_date) as weekday from orders;//获取订单日期为星期几
select order_num,DATENAME(weekday,order_date) as weekday from orders;//获取订单日期为星期几的英文单词
Day()、Month()、Year()分别为DatePart的快捷方式
 
select cust_id,order_num from orders where DATEDIFF(day,order_date,'2005-09-01')=0; //DateDiff()函数用来查明两个日期的区别.
 
select cust_id,order_num from orders where YEAR(order_date)=2005 and MONTH(order_date)=9; //找出2005年9月下的所有订单
 
数值的处理
Abs() 返回一个数的绝对值
Cos() 返回一个角度的余弦
Exp() 返回一个数的指数值
Pi() 返回圆周率
Rand() 返回一个随机数
Round() 返回四舍五入为特定长度或精度的数值
Sin() 返回一个角度的正弦
Sqrt() 返回一个数的平方根
Square() 返回一个数的平方
Tan() 返回一个角度的正切
 
数据汇总
SQL聚集函数
Avg() 返回某列的平均值
Count() 返回某列的行数
Max() 返回某列的最大值
Min() 返回某列的最小值
Sum() 返回某列之和
 
count(*) 对表中的行数目进行计算,不管表中包含的是空值(NULL)还是非空值。
count(column) 对特定列中具有值得行进行计算,忽略NULL值。
 
Avg(DISTINCT prod_price)
select AVG(distinct prod_price) as avg_price from products where vend_id=1003; //只考虑不同价格的平均值

分组数据
Group By 分组
select vend_id,COUNT(*) as num_prods from products  group by vend_id; //对每个组进行聚集
1.可以包含任意数目的列.
2.指定多个分组,在最后指定的分组上进行汇总.
3.每个列都必须是检索列或有效的表达式.select中的表达式必须和group by中一致.
4.除聚集计算语句外,select语句中的每个列都必须在group by子句中给出.
5.如果分组列中有null值,则null将作为一个分组返回.多个null视为一组.
6.group by子句必须出现在where子句之后,order by子句之前.
 
Having 过滤分组
select cust_id,COUNT(*) as orders from orders group by cust_id having COUNT(*)>=2; //使用having过滤行
select vend_id,COUNT(*) as num_prods from products where prod_price>=10 group by vend_id having COUNT(*)>=2; //同时过滤行和分组
 
子查询
select cust_id from orders where order_num in(
select order_num from orderitems where prod_id='TNT2');//查询订购物品TNT2的所有订单
*子查询总是从内向外处理.
select cust_name,cust_contact from customers where cust_id in(
select cust_id from orders where order_num in(
select order_num from orderitems where prod_id='TNT2'));//查询订购物品TNT2的所有用户

select cust_name,cust_state,(
select COUNT(*) from orders where orders.cust_id=customers.cust_id) as orders
from customers order by cust_name;//查询每个客户订单的总数
 
Exists
select cust_id,cust_name from customers where cust_id in(
select cust_id from orders where DATEDIFF(month,order_date,'2005-09-01')=0
and customers.cust_id=orders.cust_id); //使用in检索2005.09下订单的顾客

select cust_id,cust_name from customers where exists(
select * from orders where DATEDIFF(month,order_date,'2005-09-01')=0
and customers.cust_id=orders.cust_id); //使用exists检索2005.09下订单的顾客
 
联接表
联接是一种机制,用来在一条select语句中关联表,因此称之为联接.
select vend_name,prod_name,prod_price from vendors,products
where vendors.vend_id=products.vend_id order by vend_name,prod_name;
 
笛卡尔积:由没有联结条件的表关系返回的结果为笛卡尔积.检索出的行的数目将是第一个表中的行数乘以第二个表中的行数.
 
select customers.cust_id,customers.cust_name from customers,orders where
DATEDIFF(month,order_date,'2005-09-01')=0 and customers.cust_id=orders.cust_id; //找出2005年9月下的所有订单
 
内部联结 <--> 等值联结
select vend_name,prod_name,prod_price from vendors inner join products on vendors.vend_id = products.vend_id;//使用inner join方式
 
select prod_name,vend_name,prod_price,quantity,order_num from orderitems,products,vendors
where products.vend_id=vendors.vend_id and orderitems.prod_id=products.prod_id and order_num='20005' //联结多个表

select cust_name,cust_contact from customers,orders,orderitems where customers.cust_id=orders.cust_id
and orderitems.order_num = orders.order_num and prod_id='TNT2' ; //性能优于子查询方式

高级联结
*别名:1.缩短sql语句.2.允许在单条select语句中多次使用相同的表.
 
自联结
select prod_id,prod_name from products where vend_id=
(select vend_id from products where prod_id='DTNTR'); //子查询方式
select p1.prod_id,p1.prod_name from products as p1,products as p2 where
p1.vend_id=p2.vend_id and p2.prod_id='DTNTR'; //自联结方式
 
自然联结  
select c.*,o.order_num,o.order_date,oi.prod_id,oi.quantity,oi.item_price
from customers as c,orders as o,orderitems as oi
where c.cust_id=o.cust_id and oi.order_num=o.order_num and prod_id='FB';//自然联结排除多次出现使每列只返回一次.

外部联结 -- left outer join/right outer join/full outer join
select customers.cust_id,orders.order_num from customers
left outer join orders on customers.cust_id=orders.cust_id;//outer join指定联结类型

select customers.cust_id,orders.order_num from customers,orders
where customers.cust_id *= orders.cust_id; //where版的外联结,已经不支持了.

带聚集的联结
select customers.cust_name,customers.cust_id,COUNT(orders.order_num) as num_ord
from customers inner join orders on customers.cust_id = orders.cust_id
group by customers.cust_name,customers.cust_id;//



组合查询
1.在单个查询从不同的表返回类似结构的数据;
2.对单个表执行多个插选,按单个查询返回数据。
 
Union
与具有多个Where子句条件查询完成的工作相同.
select vend_id,prod_id,prod_price from products
where prod_price<=5
union
select vend_id,prod_id,prod_price from products
where vend_id in(1001,1002);
 
select vend_id,prod_id,prod_price from products
where vend_id in(1001,1002) or prod_price<=5
*列数据类型必须兼容:类型不必完全相同,但必须是SQL Server可以隐含地转换的类型.

Union All
select vend_id,prod_id,prod_price from products
where prod_price<=5
union all
select vend_id,prod_id,prod_price from products
where vend_id in(1001,1002); //包含重复的行

*只能使用一条Order By子句.

全文本搜索
使用全文本搜索,SQL Server不需要分别查看每个行,不需要分别分析和处理每个词.SQL Server创建指定列中各词的一个索引,搜索可以针对这些词进行.
设置:
1.必须对相应的数据库启用全文本搜索的支持;
2.必须定义一个目录(保存全文本数据);
3.必须对要索引的表和列建立全文本索引;
索引建立之后,可以使用带FREETEXT和CONTAINS谓词的Select具体执行搜索.

exec sp_fulltext_database 'enable';   //开启全文本支持

create fulltext catalog catalog_crashcourse;//创建名为catalog_crashcourse的目录

create fulltext index on productnotes(note_text)
key index pk_productnotes on catalog_crashcourse;//在productnotes表上创建一个全文本索引,索引的主键名pk_productnotes.on子句指定用来存储全文本数据的目录.

Alert fulltext catalog catalog_crashcourse REBUILD;//重建索引
ALTER FULLTEXT 更新,DROP FULLTEXT删除。

select * from sys.fulltext_catalogs;//查看现有目录和索引
select * from sys.fulltext_indexes;//查看定义的索引信息

FREETEXT -- 简单搜索,按意思进行匹配
select note_id,note_text from productnotes
where note_text like '%rabbit food%';//未返回任何行
select note_id,note_text from productnotes
where freetext(note_text,'rabbit food');//返回两行,进行了简单推断

CONTAINS -- 进行词或短语的搜索,也包括近似词、派生词
select note_id,note_text from productnotes where contains(note_text,'handsaw'); //在列note_text中找出词handsaw.
select note_id,note_text from productnotes where contains(note_text,'"anvil*"');//全文本搜索使用*(而不是%)作为通配符.
select note_id,note_text from productnotes where contains(note_text,'safe and handsaw');//包含safe和handsaw的行.
select note_id,note_text from productnotes where contains(note_text,'rabbit and not food');//只包含词rabbit和不包含food的行.
select note_id,note_text from productnotes where contains(note_text,'detonate near quickly');//指示搜索引擎只在项相互接近时才匹配.
select note_id,note_text from productnotes where contains(note_text,'FORMSOF(INFLECTIONAL,vary)');//指示索引查找与指定词具有相同词干的词.

*语言支持 select * from sys.syslanguages;//查询可支持的语言 直接传递Id给fulltext()即可.
*FULLTEXT搜索用FULLTEXTTABLE()函数排序,CONTAINS搜索用CONTAINSTABLE()函数排序.

select f.[rank],note_id,note_text from productnotes,freetexttable(productnotes,note_text,'rabbit food') f where productnotes.note_id=f.[key] order by [RANK] DESC;//排序搜索结果
*可使用ISABOUT()函数给特定的词赋予权重值


插入数据
Insert
insert into customers values(1006,'pep E. lapew','100 main street','los angeles','ca',
'90046','USA',null,null);//插入完整行
*此时插入失败,cust_id为标识符,需要使用Set IDENTITY_INSERT = ON来手动指定标识符字段。
INSERT INTO [customers]([cust_name],[cust_address],[cust_city],[cust_state],[cust_zip],[cust_country]
           ,[cust_contact],[cust_email])
VALUES('pep E. lapew','100 main street','los angeles','ca','90046','USA',null,null);//更安全的插入
*SQL Server不支持多个VALUES子句插入多行,只能多个INSERT一次性提交。

Insert Select  -- 导入操作
INSERT INTO [customers]([cust_name],[cust_address],[cust_city],[cust_state],[cust_zip],[cust_country]
           ,[cust_contact],[cust_email])
select [cust_name],[cust_address],[cust_city],[cust_state],[cust_zip],[cust_country],[cust_contact],[cust_email]
from custnew;

Select Into -- 到出操作
select cust_contact,cust_email,cust_address,cust_city,cust_state,cust_zip,cust_country
into customersExport from customers;//customersExport必须不存在

更新和删除数据
Update customers
set cust_email='elmer@fudd.com'
where cust_id=10005;//更新基本操作
Update customers
Set cust_email = null; //清除列

delete from customers where cust_id=10006;//删除基本操作
*TRUNCATE TABLE 更高效的删除

 创建和操纵表
CREATE TABLE
create table customers(
cust_id int not null identity(1,1),
cust_name nchar(50) not null,
primary key (cust_id)
);//identity(seed,increment)自动增量.
*select @@identity as newId 获取增量值
create table orderitems(
order_num int not null,
order_item int not null,
prod_id nchar(10) not null,
primary key(order_num,order_item)
);//指定多个主键

ALTER TABLE
alter table vendors add vend_phone char(20);
alter table vendors drop column vend_phone;

DROP TABLE
drop table customers;

sp_rename 重命名表
EXEC sp_rename 'customers2','customers';

使用视图
视图是虚拟的表,它不包含任何列或数据,它包含的是一个SQL查询。
1)重用SQL语句;2)简化复杂的SQL操作;3)使用表的组成而不是整个表;3)保护数据;4)更改数据格式和表示。
1)视图不能超过1024列;2)Order By不可以用在视图中;3)视图不能索引;

CREATE VIEW
create view productcustomers as
select cust_name,cust_contact,prod_id from customers,orders,orderitems
where customers.cust_id=orders.cust_id and orderitems.order_num=orders.order_num;

create view vendorlocations as
select RTrim(vend_name) + ' (' + RTrim(vend_country)+ ') ' as vend_title from vendors;

create view customermaillist as
select cust_id,cust_name,cust_email from customers where cust_email is not null;

create view orderitemsexpanded as
select order_num,prod_id,quantity,item_price,quantity*item_price as expanded_price from orderitems;

T-SQL程序设计
DECLARE
declare @age int;//声明age变量

SET
set @age=21;//给变量赋值

SELECT
select @age=21;//给变量赋值
select @age;//查看变量内容

PRINT
print @age;//输出文本

IF
declare @open bit
if DatePart(dw,getdate())=1
   set @open=0
else
   set @open=1
select @open as OpenForBusiness

OR
declare @open bit
dellcare @dow int
set @dow = datepart(dw,getdate());
if @dow =1 or @dow=7
   set @open=0
else
   set @open=1
select @open as OpenForBusiness

BEGIN END
declare @dow int
declare @open bit,@process bit
set @dow = datepart(dw,getdate())
if @dow =1 @dow=7
   begin
        set @open =0
        set @process=0
   end
else
   begin
        set @open=1
        set @process=1
   end

WHILE
declare @counter int
set @counter=1
while @counter<=10
begin
    print @counter
    set @counter=@counter+1
end

BREAK:退出while循环
CONTINUE:在循环起始处开始处理

使用存储过程
一条或多条T-SQL语句的集合.
EXECUTE
execute productpricing @cheap output,@expensive output,@average output ;
CREATE PROCEDURE
create procedure productpricing as
begin
    select avg(prod_price) as priceaverage from products;
end;

DROP PROCEDURE  删除存储过程

定义:createprocedure productpricing
@price_min money output,@price_max money output,@price_avg money output
as
begin
select @price_min = min(prod_price) from products;
select @price_max = max(prod_price) from products;
select @price_avg = avg(prod_price) from products;
end;
调用:declare @cheap money
declare @expensive money
delcare @average money
execute productpricing @chaep output,@expensive output,@average output

定义:create procedure ordertotal @order_num int,@order_total money output
as
begin
select @order_total = sum(item_price*quantity) from orderitems where order_num=@order_num;
end;
调用:declare @order_total money
execute ordertotal 20005,@order_total output
select @order_total

定义:create procedure ordertotal @order_num int,@taxable bit,@order_total money output
as
begin
declare @total money;
declare @taxrate int;
set @taxrate=6;
select @total=sum(item_price*quantity)
from orderitems
where order_num=@order_num
if @taxable=1
   set @total=@taotal+(@total/100*@taxrate);
select @order_total=@taotal;
end;
调用:declare @order_total money
execute ordertotal 20005,0,@order_total output

使用游标
游标是一个存储在SQL Server上的数据库查询,它不是一条SELECT语句,而是被该语句检索出来的结果集.
DECLARE name CURSOR
declare orders_cursor cursor for
select order_num from orders order by order_num;
DEALLOCATE orders_cursor;

OPEN orders_cursor;
在open语句时执行查询,存储检索出得数据以供浏览和滚动.

CLOSE orders_cursor;
colse释放游标使用的所有内存和内部资源.

FETCH
fetch语句分别访问游标的每一行.
declare @ordder_num int;
declare orders_cursor cursor for
select order_num from orders order by order_num;
open orders_cursor;
fetch next from orders_cursor into @order_num;
close orders_cursor
deallocate orders_cursor;

FETCH FIRST/LAST/PRIOR/ABSOLUTE/RELATIVE/

declare @ordre_num int;
declare orders_cursor cursor fro
select order_num from orders order by order_num;
open orders_cursor;
fetch next from orders_cursor into @order_num;
while @@fetch_status=0
begin
  fetch next from orders_cursor into @order_num;
end
close orders_cursor
deallocate orders_cursor;
@@fetch_status 如果fetch成功,返回0,否则返回一个负值.

declare @order_num int;
declare @order_total money;
declare @total money;
set @total=0;
declare orders_cursor cursor fro
select order_num from orders order by order_num;
open orders_cursor;
fetch next from orders_cursor into @order_num;
while @@fetch_status =0
begin
execute ordertotal @order_num,1,@order_total output
set @total=@total+@order_total
fetch next from orders_cursor into @order_num;
end
close orders_crusor
deallocate orders_cursor;
select @total as granttotal;

使用触发器
触发器是SQL Server响应以下任意语句而自动执行的一条T-SQL语句:
DELETE;
INSERT;
UPDATE

CREATE TRIGGER
create trigger newproduct_trigger on products
after insert as select 'prodcut added';

DROP TRIGGER\DISABLE TRIGGER\ENABLE TRIGGER

SP_HELPTRIGGER table
取一个表名并返回触发器的一个列表.

事务处理
事务处理用来维护数据库的完整性,它保证成批的T-SQL操作要么完全执行,要么完全不执行.
事务(transaction)指一组SQL语句;
回退(rollback)指撤销指定SQL语句的过程;
提交(commit)指将未存储的SQL语句写入数据库表;
保留点(savepoint)指事务处理中设置的临时占位符,可以对它发布回退.

BEGIN TRANSACTION/ROLLBACK
select * from orderitems;
begin transaction;
delete from orderitems;
select * from orderitems;
rollback;
select * from orderitems;

COMMIT
begin transaction;
delete from orderitems where order_num =20010;
delete from orders where order_num = 20010;
commit;

TRANSACTION delete1

SET IMPLICIT_TRANSACTIONS ON
设置是否不需要COMMIT语句就自动提交更改.

使用XML
FOR XML
select vend_id,RTrim(vend_name) as vend_name from vendors order by vend_name for xml auto;//指示生成xml的输出

RAW/ELEMENTS
select vned_id as id,RTrim(vend_name) as name from vendors order by vend_name fro xml raw('vendor'),root('vendors'),elements;
elements关键字导致列作为子元素嵌入.RAW允许指示行标记名,ROOT用来指定顶层标记名.

XML数据访问
exist,modify,nodes,query,value.
select data.query('/state/city') from myXmlTable;
select * from myXmlTable where data.exist('/state/city[@name="chicago"]')=1;

 全球化和本地化
 FN_HELPCOLLATIONS()
select * from  FN_HELPCOLLATIONS();//返回可用的校对顺序

SERVERPROPERTY()
select SERVERPROPERTY('collation') as collation;//默认校对顺序

DATABASEPROPERTYEX()
select databasePropertyEx('Crash Course','Collation') as collation;//定义校对顺序

create table mytable(
column1 int,
column2 varchar(10) collate hebrew_ci_ai
);//为不同的列指定校对顺序

select * from customers order by cust_name COLLATE SQL_Latin1_General_CP1_CS_AS;//select语句指定校对顺序

'N'前缀
insert into mytable(column1,column2) values(1000',N'ěㄝΥ');//任何时候使用Unicode串都必须指定N前缀.

安全管理
sp_helplogins
exec sp_helplogins;//检索数据库用户

CREATE LOGIN
create login Benf WITH password='p@$$w0rd';
*05之前的版本用:exec sp_addlogin 'Benf','p@$$w0rd';

DROP LOGIN user

ALTER LOGIN benf DISABLE/ENABLE

ALTER LOGIN
alter login benf with name = benforta;
alter login benf with password ='n3w p@$$w0rd';

GRANT
grant create table to benf;  //授予create table访问权限

REVOKE
revoke create table from benf;

posted @ 2011-11-25 17:21 冰の酷龙 阅读(15) 评论(0)  编辑

      今天TFS又出问题,之前一直映射好的项目打开TFS后居然显示未映射:

      想可能是映射失效了,把映射再编辑一次即可.结果报错:

    

在网上找到了解决办法:

在文件 C:/Documents and Settings/当前用户/Local Settings/Application Data/Microsoft/Team Foundation/1.0/Cache/VersionControl.config 中,缓存了本地文件夹到旧服务器的一些映射关系,只要把跟旧服务器相关的 ServerInfo 节点删掉,问题即可解决。

如果是windows 7的操作系统,路径有点变化:

 C:/Users/Administrator/AppData/Local/Microsoft/Team Foundation/1.0/Cache/VersionControl.config 中,缓存了本地文件夹到旧服务器的一些映射关系,只要把跟旧服务器相关的 ServerInfo 节点删掉,问题即可解决.

我按照方法,但是仍然报错了:

到了这里我都打算放弃了,重新映射一个地址算了,但是觉得这样放弃不好,再想想可能就有办法了.

上面的doku和pjl使我想起一个事情,因为tfs分配给我的账号是pjl,但是我的计算机名是doku,有一次不能登陆tfs,又分配了一个doku的账号给我.

今天我登陆了一次tfs服务器,而且保存了密码.而登陆tfs又不用输入密码.至此,我算是想明白了.在凭证管理器中看到这罪魁祸首:

将其删除,再打开vs时,即可出现tfs登陆界面,输入正确的账户即可.总算是解决了这问题.

posted @ 2011-10-20 11:37 冰の酷龙 阅读(18) 评论(0) 编辑

     错误信息:响应消息的内容类型 text/html; charset=utf-8 与绑定(text/xml; charset=utf-8)的内
容类型不匹配。如果使用自定义编码器,请确保正确实现 IsContentTypeSupported 方法。


    今天小姚给客户做远程的时候出现这问题,第一感觉应该是配置出了问题,但小姚说客户并没有动过配置文件。程序

一直运行很好,直到给服务器做了一些安全配置。没有测试环境,一时无头绪,只好借助Google搜索,没有得到预期的答案。

    小姚说IIS下的Web Service也打不开,这才引起我的注意,习惯性的看了下应用程序日志,发现一片飘红。都是说这进程未启动:

    aspnet_wp.exe 未能启动  

    以为这就解决问题了,但是按照网上提供的方法:更改machine.config文件

         它位于C:\WINNT\Microsoft.NET\ Framework\v1.0.3705(asp.net 1.0是这样,如果你的版本是1.1,文件夹名回不同)\CONFIG\,

将里面一个部件<processModel>中的 username的属性设置为SYSTEM,正因为它原来默认的设置为machine。(PS:2.0的配置文件是:machine.config.comments)

    还是没有效果,后来这两篇文章给了我灵感:

http://blog.donews.com/litterboy/archive/2005/10/11/584183.aspx/

http://xu020408.blog.163.com/blog/static/26548920093238128640/

    查看了下姚的配置Microsoft.NET\Framework\v2.0.50727的安全配置,发现比客户服务器中的安全配置多了一个IUSER_***的用户,将此用户添加到安全配置中.

冲起下IIS,马上可以访问了.

    PS:iisreset IIS重起

         aspnet_regiis.exe -i  aspnet重新注册

两个命令很久没用,全给忘光了~

posted @ 2011-10-07 15:20 冰の酷龙 阅读(121) 评论(0) 编辑
摘要: 今天给客户导入数据,发现有一列出现很多为null的数据。在使用Sql Server数据导入的时候,数据类型默认为了float,怎么都不能改变其类型。只要求助万能的网络,于是用google搜到一篇:http://hi.baidu.com/qwwwwqwwww/blog/item/7fa251088eea7ada63d98660.html 在Excel中,我们时常会碰到这样的字段(最常见的就是电话号码),即有纯数字的(如没有带区号的电话号码),又有数字和其它字符混合 (如“区号-电话号码”)的数据,在导入SQLServer过程中,会发现要么纯数字的数据导过去之后变成了NULL,要么就是数字和其它.阅读全文
posted @ 2011-09-07 11:33 冰の酷龙 阅读(115) 评论(0) 编辑
摘要: 浏览器兼容就比较让人恼火,公司来了新领导以后一定要求与Firefox兼容,无可厚非,但是开发部就那么3,4杆枪,连需求完成都有问题,美工又不会js,我的js也是半桶水,能完成功能就不错了,还要去兼容。。。。(省略1000字抱怨) 兼职测试的客服人员报告,有个弹出窗口在FF下无法关闭。因为之前有过js不兼容firefox的情况,所以很快锁定问题: window.close()不执行. 上次是因为: window.navigate(redirectTo); Firefox下不支持,所以很容易搜索出替代方案: window.location.href = redirectTo; 这次没那么好运了,.阅读全文
posted @ 2011-08-27 15:16 冰の酷龙 阅读(95) 评论(0) 编辑
摘要: 最近在做接口程序,Web服务器又不能访问外网,只能通过另一台有网的服务器转出去。折腾了几天,真是受不了。还好接近尾声了,碰到个很有意思的问题。在最后生成服务的时候报错,HRESULT = '80004005'。还好有Google,不然不知道啥时才能解决呢。【产生原因】解决方案中的某些项目已被其他版本的vs修改,如当前解决方案是使用vs2008创建使用的,而解决方案中的某些项目被vs2010打开修改,当重新用vs2008打开项目并生成安装包时,出现此错误。【处理方法】使用外部文本编辑器如记事本打开相关项目文件(*.csproj),即上述所说的{关注此项目名字}。找到类似行:<阅读全文
posted @ 2011-06-14 14:54 冰の酷龙 阅读(119) 评论(0) 编辑
摘要: 用SQL Server Profiler跟踪SQL的时候,老是出现下面的执行.而且不间断,隔几秒就会出现一次,很是恼火.找了半天,发现是ReportServer数据库里面的表.但是总不能删掉这个数据库把.后来网上找了下,关掉Report服务就行了,打开Reporting Services配置管理器,停掉服务,总算清静了.继续优化项目.declare @BatchID uniqueidentifier set @BatchID = newid() UPDATE [Notifications] WITH (TABLOCKX) SET [BatchID] = @BatchID, [ProcessS.阅读全文
posted @ 2011-05-06 15:40 冰の酷龙 阅读(58) 评论(0) 编辑