sql技巧

来源:互联网 发布:百度软件开发平台 编辑:程序博客网 时间:2024/04/30 13:03

需要排序且要连接两个表使用:Union
select top 15  * from (select UInfoId as id,DateTime from T_UInfo where MarketId='" + findID + "' union select CouponId as id,DateTime from T_Coupon where MarketId='" + findID + "') b order by CreationDateTime desc

根据(左/右)表选择需要的列
左连接left join tbname on a.id=b.id 以左表为基础,右表没有左表的就为空
右连接right join tbname on a.id=b.id 与左连接相反
inner join并不以谁为基础,它只显示符合条件的记录ON
inner join 与select两个表where效果等同

连接两个相同结构的表 :select id from A union select id from B

查询日期: select substring(convert(char,year(getdate())),3,2)

存储过程中:SET NOCOUNT 为 ON 时不返回计数(影响的行数)可显著提高性能。
当OFF 时,返回计数

数为NULL时候:isnull(r.r_content, '暫未回復!') as r_content

用tb1的字段更新tb2的字段(两表通过ID联系)
update tb1 set tb1.sort_name=tb2.sort_name from tb2 where tb1.ID=tb2.ID

--这样可以防止更新错误,或忘记加条件把所有数据都更新
--当为off 时候只回滚出错的语句,为on时候全不回滚
SET XACT_ABORT on
begin tran

update admin set pwd='kkk' where id='123'
--确认时候执行提交
commit tran
--出错时候执行回滚
rollback tran

实现随机查询:order by newid()

实现过滤“'”单引号,把他替换成“''”两个单引号即可,由数据库的命名规则决定。
------------------------------------------------------------------------
查找回车的索引:CHARINDEX(CHAR(13)
截取第一个回车前的字串,没有就截取默认长度

SUBSTRING(content, 1, CASE WHEN CHARINDEX(CHAR(13), content)> 0 THEN CHARINDEX(CHAR(13), content) ELSE 20 END) AS content

---------------------------------------------------------------

插入记录时同时取得自增列的编号 insert into photos(photoID) values(11);select @@IDENTITY;