SQL server一些笔记

-------通过字段名 获得表名
SELECT sb.name
FROM syscolumns s JOIN sysobjects sb ON s.id=sb.id
WHERE s.name='你的字段名'

left join(左联接) 返回包括左表中的所有记录和右表中联结字段相等的记录
right join(右联接) 返回包括右表中的所有记录和左表中联结字段相等的记录
inner join(等值连接) 只返回两个表中联结字段相等的行

举例如下:
--------------------------------------------
表A记录如下:
aID     aNum
1     a20050111
2     a20050112
3     a20050113
4     a20050114
5     a20050115

表B记录如下:
bID     bName
1     2006032401
2     2006032402
3     2006032403
4     2006032404
8     2006032408

--------------------------------------------
1.left join
sql语句如下:
select * from A
left join B
on A.aID = B.bID

结果如下:
aID     aNum     bID     bName
1     a20050111    1     2006032401
2     a20050112    2     2006032402
3     a20050113    3     2006032403
4     a20050114    4     2006032404
5     a20050115    NULL     NULL

(所影响的行数为 5 行)
结果说明:
left join是以A表的记录为基础的,A可以看成左表,B可以看成右表,left join是以左表为准的.
换句话说,左表(A)的记录将会全部表示出来,而右表(B)只会显示符合搜索条件的记录(例子中为: A.aID = B.bID).
B表记录不足的地方均为NULL.


-----------循环表

declare @id int
declare @maxid int
set @id=3
select @maxid=max(id) from 表名
begin
while @id<=@maxid
begin
update 表名 set avg_value=balance+(select avg_value from test where id=@id-1) where id=@id
set @id=@id+1
end
end

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

select sq, count(crbnum) as gs from mytest3 GROUP BY sq

------------------------------------
string转换成int型

cast('字符串型数字' as int)

-------------------------------------
truncate table 表名 ---清空一张表

-------查询一张表中字段相同的数据
select * from '表名' where '查找字段名' in(select '查找字段名' from '表名' Group By '查找字段名' HAVING(count(*))>1 )

--所有表列名
declare @col varchar(1000)
set @col=''
select @col=@col+','+name from syscolumns where id=object_id('表名')
set @col=stuff(@col,1,1,'')
select @col


CONVERT(VARCHAR(19),#SWRQ#,121) --SQL转成年月日时分秒


select * from sys.servers 查询数据库关联关系

-- 把字符串 倒过来
DECLARE @Name NVARCHAR (50)
set @Name='闵s-34-25' (52-43-s闵)
select reverse(@Name)

posted @ 2016-11-05 15:29  潜水洗头  阅读(149)  评论(0编辑  收藏  举报