Sql常用语句汇总(2009-03-18 21:24:55)
//基本语句
SqlServer 查询Access语句
SELECT * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0', 'c:\youfile.mdb';'admin';'youpwd',youtabname) AS a
新建表:create table [表名] ([字段一],[类型],[是否为空],…)
例: create table mytry(
name char(5) not null,
code smallint identity(1000,1)) //将code设为自动递增的数据,从1000依次递增1
新增:insert into [表名] ([字段一],[字段二],…) values ('aa','bb',…) where … ;
更新:update [表名] set [字段一]='aa',[字段二]='bb' where …
删除:delete from [表名] where …
查找:select [字段一](as…),[字段二],… from [表名] where …
新加字段
access:alter table tableName add[alter] column columnName columnType
sqlserver:alter table tableName add[alter] columnName columnType
通配符
like:
反向:'037001002' like '%' + unitId + '%' //反向查找添加通配符后等于指定符的记录
正向:unitId like '%037001002%' //正向查找包括指定符的记录
%:任意匹配
_:匹配一个字符,一个汉字等于两个字符:'__'
WHERE au_fname LIKE '_ean' 将查找以 ean 结尾的所有 4 个字母的名字(Dean、Sean 等)。
注:access中以?代替
[]:通配符:WHERE au_lname LIKE '[C-P]arsen' 将查找以arsen 结尾且以介于 C 与 P 之间的任何单个字符开始的作者姓氏,例如,Carsen、Larsen、Karsen 等。
[^]:非:WHERE au_lname LIKE 'de[^l]%' 将查找以 de 开始且其后的字母不为 l 的所有作者的姓氏。
escape:逃逸字符如 like '张#%%三' escape '#' ,为查找 张%某某的人
select a.* from a,(……)b where a.id like b.id+'%'
条件成熟后操作:SELECT
(CASE WHEN EXISTS (SELECT * FROM view_name WHERE user_id = '1')
THEN user_id END),user_name //user_id为选择字段
FROM view_name
按组查询:(当有统计函数,普通字段)
SELECT codeid, SUM(codelevel) AS 水平
FROM wdc_ts_code
GROUP BY codeid
创建视图:
create view myview as (select …)
最右/最左一位
right(字段,位数) = '匹配字符串'/left(字段,位数) = '匹配字符串'
空字段
字段 is null
建表及主键
CREATE TABLE [dbo].[uploadFiles1]
(
[id] [int] IDENTITY (1, 1) NOT NULL,
PRIMARY KEY (id,……)
) ON [PRIMARY]
或
CREATE TABLE [dbo].[uploadFiles1]
(
[id] [int] IDENTITY (1, 1) NOT NULL primary key
) ON [PRIMARY]
批量更新,多表链接
UPDATE A004A001
SET status = '1000000000'
FROM A004A001 INNER JOIN
(SELECT MAX(id) AS id, A0100
FROM A004A001
GROUP BY A0100) AS b ON A004A001.A0100 = b.A0100 AND A004A001.ID = b.ID
UPDATE SR_BuiltItem INNER JOIN SR_SourceItem ON (SR_BuiltItem.FieldName = SR_SourceItem.FieldName) AND (SR_BuiltItem.SetId = SR_SourceItem.SetId) SET SR_BuiltItem.Description = [SR_SourceItem].[Description];
参数声明
strSql=@"declare @MaxId int;Select @MaxId="+ dr["Cx_MainID"].ToString() +";"; (strSql=@"declare @MaxId int;select @MaxId=(Select IsNull(Max(Cx_MainID),0)+1 From SR_CxMain);";)
strSql+="Delete From SR_CxMain Where Cx_MainID=@MaxId;";
//精妙语句
1、复制表(创建):