您的位置:首页 > 数据库

SQL Server 的SQL基础知识

2014-05-17 19:35 274 查看
1.N'关闭'N是指nvarchar,是将其内容关闭作为 Unicode字符常量(双字节)。而没有N的 '关闭', 是将关闭作为字符常量(单字节)。

平常没有加N,结果里面直接出现?. 具体如下图:





2.IF OBJECT_ID('dbo.Employees','U') IS NOT NULL --U检查Employees表是否已经存在当前数据库中。其中U代表用户表。

3.

以结果集结构创建表
"select * into temp from 表(结果集) where 1=1(将数据一并插入到新表),
where 1=2(创建空表,结构同结果集)"

获取所有表的记录数
if object_id( 'tempdb..#tablecount ') is not null drop table #tablecount
select cast(null as sysname) as 表名称, 1 as 记录数 into #tablecount where 1 = 0

declare @TableName sysname
declare testcur cursor for select [name] from sysobjects where xtype = 'U ' order by [name]
open testcur
fetch next from testcur into @TableName
while @@fetch_status = 0
begin
exec( 'insert into #tablecount select ''' + @TableName + ''', (select count(1) from ' + @TableName + ') ')
--exec('select * from ' + @TableName)
fetch next from testcur into @TableName
end
close testcur
deallocate testcur
--select * from #tablecount order by 记录数
--drop table #tablecount

4.不同的 SQL JOIN

除了我们在上面的例子中使用的 INNER JOIN(内连接),我们还可以使用其他几种连接。

下面列出了您可以使用的 JOIN 类型,以及它们之间的差异。

JOIN: 如果表中有至少一个匹配,则返回行

LEFT JOIN: 即使右表中没有匹配,也从左表返回所有的行

RIGHT JOIN: 即使左表中没有匹配,也从右表返回所有的行

FULL JOIN: 只要其中一个表中存在匹配,就返回行

5.SQL Server如何将Id相同的字段合并,并且以逗号隔开。

例: id name
1 张三
1 李四
2 王五
2 赵六
结果:
Id name

1 张三,李四
2 王五,赵柳

SQL脚本:

use testdb

create table testA
(
id int,
name nvarchar(32)
)

Insert into testA(id,name) values(1,'张三')
Insert into testA(id,name) values(1,'李四')
Insert into testA(id,name) values(2,'王五')
Insert into testA(id,name) values(2,'赵六')

select id,(select ','+name from testA where a.id = id for xml path('')) as name
,stuff((select ','+name from testA where a.id = id for xml path('')),1,1,'') as name2
from testA a
group by id


结果如下:



参考:http://zhidao.baidu.com/link?url=2oFbIL6joG7Htfgzc28gCV2Pd1hYzu3Alds05vB9BMfg2SpVCkLEZCgtgb4lwnf64WHnTwhF85b1rYX-Vpi3Gq&qq-pf-to=pcqq.c2c

STUFF
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: