写sql语句时候遇到的一些问题
Posted 东方华夏
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了写sql语句时候遇到的一些问题相关的知识,希望对你有一定的参考价值。
CS0436 异常警告,vs中有可能是自己引用自己造成的)
批量替换
update 表名 set code=replace(code,原来值,修改值) where countyid=\'\';
sql 截取字符串
https://www.cnblogs.com/xielong/p/7670757.html
substr(SUBITEM,instr(SUBITEM,\'*\',1)+1)
其中,使用了substr函数和instr函数。
1、substr(string,start_position,[length])求子字符串,返回字符串
第一个参数表示要截取的字符串,第二个表示起始位置,第三个表示截取的长度,可省略。
2、instr(string,subString,position,ocurrence) 查找字符串的位置
第一个参数表示源字符串,第二个是要查找的字符,第三个是要查找的开始位置,第四个是查找的字符是第几个。
1.给某列前面增加字符:
UPDATE 表名 SET 列名=\'要添加的字符\'|| 列名
例如 substr((\'xx\' || 字段名), 1, 8) 在字段前用\'||\'添加86,然后substr截取8位
2.给某列后面增加字符:
UPDATE 表名 SET 列名=列名||\'要添加的字符\'
//oracle 数据库
select nvl(t1.rscount, 0) as rscount,
字段
from (select count(0) as rscount, substr((\'86\'||字段),1,8) as 字段
from 表 a
where 字段 in
(select 字段 from 表 where 字段 like \'xxx%\')
and to_date(\'2018-09-01\', \'yyyy-mm-dd\') <= a.CREATEDATE
and (to_date(\'2018-12-31\', \'yyyy-mm-dd\') + 1) > a.CREATEDATE
group by 字段) t1,
(select 字段
from 表 b
where 字段 like \'xxx%\'
and length(trim(b.字段)) = length(trim(\'xxx\')) + 2
and b.ISACTIVE = 1
order by b.idx asc) t2
where t1.字段(+) = trim(t2.字段)
---- ////////////////////////////////////////////////////
select t1.rscount,t1.字段, t2.字段
from (select count(a.字段) as rscount,
TO_CHAR(CREATEDATE, \'yyyy-mm\') timevalue,
substr((\'xx\'||a.shiguid),1,8) as 字段
from 表 a
where 字段 in
(select trim(字段) from 表 where 字段 like \'xxx%\')
group by 字段,TO_CHAR(CREATEDATE, \'yyyy-mm\')) t1,
(select \'2018-\' || lpad(level, 2, 0) datevalue
from dual
connect by level < 13) t2
where t1.字段(+) = t2.字段 and (t1.字段=\'xxxxxx\'or t1.字段 is null)
order by t2.字段
///////////////////////////////////
oracle错误ora-01658的解决办法
此错误是报oracle的表空间大小不足。首先查看所有表空间的大小:
SELECT T.TABLESPACE_NAME, ROUND(SUM(BYTES/(1024 * 1024)), 0) TS_SIZE
FROM DBA_TABLESPACES T, DBA_DATA_FILES D
WHERE T.TABLESPACE_NAME = D.TABLESPACE_NAME
GROUP BY T.TABLESPACE_NAME;
然后查询要修改的表空间的数据文件名:
select file_name,blocks,tablespace_name
from dba_data_files
将对应表空间的dpf文件路径记下来。比如‘/opt/oracle/oradata/TEST/test.dbf’
最后修改表空间数据文件:
ALTER DATABASE DATAFILE \'/opt/oracle/oradata/TEST/test.dbf\' RESIZE 2000M;
////////////////////////////////////////////////tianjia
create table xt_dict as
select * From lrmdb_t.xt_dict
////////////////////////2018-12-18//////////////////////////////////////////////////////////
update 表 set 字段=(to_date((select 字段 from 表 t where 字段=\'xxxx\'),\'yyyy-mm-dd\')+9) where 字段=\'20181012173136289-D3862BAEF48F4EBFA12CCCC0BFFFF844\'
////////////////////////2018-12-20/////////////////////////////////
显然用to_date(time, \'yyyy-mm-dd\')直接转是不行的,得先用to_char(time, \'yyyy-MM-dd\')格式化一下。
最后变成这样to_date(to_char(time, \'yyyy-MM-dd\'), \'yyyy-mm-dd\'),就不会报ORA-01861了。
//////////////////////////////////////////2019-1-16//////////////////
select * from 表 where 字段 in(select 字段 from 表 group by 字段 having count(字段)>1)
查找记录大于1的
///////////////////////////////////////////////////2019-1-17//////////////////
select top 20 * from WZ_GTYW except select top 13 * from WZ_GTYW where 查询指定行数
sql 替换字段中的部分字符,替换指定字符
把列中凡是有2011的全部修改成2014,如 lieming 里的201101131431改成201401131431,写法:
update tab set lieming = replace(lieming,\'2011\',\'2014\');
//////////////////////////////////////////////////2019-2-22//////////////////////////////////
https://www.cnblogs.com/cjm123/p/7940371.html sql 连接
select * from T_student s full join T_class c on s.classId = c.classId 全连接
//////////////////////////////////////////////////2019-03-08/////////////////////////////////////////////////////////////
Oracle中 如何用一个表的数据更新另一个表中的数据
merge into 表
using (select t.字段 ,max(t.字段) 字段 from 表 t group by t.字段)表
on (字段 = 字段)
when xxx then
update set 字段 = 字段
////////////////////////////////////////////////2019-3-20/////////////////////////////////////////////////////////////////////////
在SqlServer 中,,批量替换某个字段类型
-- 关闭 约束
declare tb cursor for
SELECT sql=\'alter table [\'+d.name+\'] NOCHECK CONSTRAINT all\'
FROM syscolumns a left join systypes b on a.xtype=b.xusertype
inner join sysobjects d on a.id=d.id and d.xtype=\'U\' and d.name<>\'dtproperties\'
where b.name in(\'decimal\') GROUP BY d.name
declare @sql1 varchar(1000)
open tb
fetch next from tb into @sql1
while @@fetch_status = 0
begin
print @sql1
exec(@SQL1)
fetch next from tb into @sql1
end
close tb
deallocate tb
-- 修改字段数据类型
declare Test1 cursor for
SELECT sql=\'alter table [\'+d.name+\'] alter column [\'+a.name+\'] int\'
FROM syscolumns a left join systypes b on a.xtype=b.xusertype
inner join sysobjects d on a.id=d.id and d.xtype=\'U\' and d.name<>\'dtproperties\'
where b.name in(\'decimal\') order by d.name,a.name
declare @sql2 varchar(1000)
open Test1
fetch next from Test1 into @sql2
while @@fetch_status = 0
begin
print @sql2
exec(@SQL2)
fetch next from Test1 into @sql2
end
close Test1
deallocate Test1
-- 恢复 约束
declare tb cursor for
SELECT sql=\'alter table [\'+d.name+\'] CHECK CONSTRAINT ALL\'
FROM syscolumns a left join systypes b on a.xtype=b.xusertype
inner join sysobjects d on a.id=d.id and d.xtype=\'U\' and d.name<>\'dtproperties\'
where b.name in(\'decimal\') GROUP BY d.name
declare @sql3 varchar(1000)
open tb
fetch next from tb into @sql3
while @@fetch_status = 0
begin
print @sql3
exec(@SQL3)
fetch next from tb into @sql3
end
close tb
deallocate tb
////////////////////////////////////////////////2019-03-28////////////////////////////////////////////////////////////////////////////
--SQL
--快速查看表结构
SELECT CASE WHEN col.colorder = 1 THEN obj.name
ELSE \'\'
END AS 表名,
col.colorder AS 序号 ,
col.name AS 列名 ,
ISNULL(ep.[value], \'\') AS 列说明 ,
t.name AS 数据类型 ,
col.length AS 长度 ,
ISNULL(COLUMNPROPERTY(col.id, col.name, \'Scale\'), 0) AS 小数位数 ,
CASE WHEN COLUMNPROPERTY(col.id, col.name, \'IsIdentity\') = 1 THEN \'1\'
ELSE \'\'
END AS 标识 ,
CASE WHEN EXISTS ( SELECT 1
FROM dbo.sysindexes si
INNER JOIN dbo.sysindexkeys sik ON si.id = sik.id
AND si.indid = sik.indid
INNER JOIN dbo.syscolumns sc ON sc.id = sik.id
AND sc.colid = sik.colid
INNER JOIN dbo.sysobjects so ON so.name = si.name
AND so.xtype = \'PK\'
WHERE sc.id = col.id
AND sc.colid = col.colid ) THEN \'1\'
ELSE \'\'
END AS 主键 ,
CASE WHEN col.isnullable = 1 THEN \'1\'
ELSE \'\'
END AS 允许空 ,
ISNULL(comm.text, \'\') AS 默认值
FROM dbo.syscolumns col
LEFT JOIN dbo.systypes t ON col.xtype = t.xusertype
inner JOIN dbo.sysobjects obj ON col.id = obj.id
AND obj.xtype = \'U\'
AND obj.status >= 0
LEFT JOIN dbo.syscomments comm ON col.cdefault = comm.id
LEFT JOIN sys.extended_properties ep ON col.id = ep.major_id
AND col.colid = ep.minor_id
AND ep.name = \'MS_Description\'
LEFT JOIN sys.extended_properties epTwo ON obj.id = epTwo.major_id
AND epTwo.minor_id = 0
AND epTwo.name = \'MS_Description\'
WHERE obj.name = \'XS\'--表名
ORDER BY col.colorder ;
//////////////////////////////////////////////////2019-03-28///////////////////////////////////////////////////////////////////////////////
sql 排序
select * from (select ROW_NUMBER()over(order by id desc) as rowNum, * from (SQL 语句) as Y) as t where rowNum>10 and rowNum<=20
SELECT TOP 10 * from (SELECT ROW_NUMBER() OVER (ORDER BY ID desc) AS RowNumber,* FROM ( sql 语句 或者表名)AS B) as A where rownumber>10
////////////////////////////////////////////////////2019-04-17///////////////////////////////////////////////////////////////////////////////
str = str.Replace("\'", "");
str = str.Replace("<", "");
str = str.Replace(">", "");
str = str.Replace("%", "");
str = str.Replace("\'delete", "");
str = str.Replace("\'\'", "");
str = str.Replace("\\"\\"", "");
str = str.Replace(",", "");
str = str.Replace(".", "");
str = str.Replace(">=", "");
str = str.Replace("=<", "");
str = str.Replace("-", "");
str = str.Replace("_", "");
str = str.Replace(";", "");
str = str.Replace("||", "");
str = str.Replace("[", "");
str = str.Replace("]", "");
str = str.Replace("&", "");
str = str.Replace("#", "");
str = str.Replace("/", "");
str = str.Replace("-", "");
str = str.Replace("|", "");
str = str.Replace("?", "");
str = str.Replace(">?", "");
str = str.Replace("?<", "");
str = str.Replace(" ", "");
/////////////////////////////////////////////////////20190509////////////////////////////////////////////////////////////////////////////////////
System.ServiceProcess.ServiceController sc = new System.ServiceProcess.ServiceController("TLKJ_TASK_CLIENT");
if (sc.Status == System.ServiceProcess.ServiceControllerStatus.Running)
{
log4net.WriteLogFile("准备关闭服务", 55);
sc.Stop();
sc.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Stopped); //等待服务停止
if (sc.Status == System.ServiceProcess.ServiceControllerStatus.Stopped)
{
sc.Start();
log4net.WriteLogFile("成功开启服务",55);
}
}
/////////////////////////////////////////////////////20190524/////////////////////////////////////////////////////////////////////////////////////////////
sql server 查询数据结构
SELECT
表名 = Case When A.colorder=1 Then D.name Else \'\' End,
表说明 = Case When A.colorder=1 Then isnull(F.value,\'\') Else \'\' End,
字段序号 = A.colorder,
字段名 = A.name,
字段说明 = isnull(G.[value],\'\'),
标识 = Case When COLUMNPROPERTY( A.id,A.name,\'IsIdentity\')=1 Then \'√\'Else \'\' End,
主键 = Case When exists(SELECT 1 FROM sysobjects Where xtype=\'PK\' and parent_obj=A.id and name in (
SELECT name FROM sysindexes WHERE indid in( SELECT indid FROM sysindexkeys WHERE id = A.id AND colid=A.colid))) then \'√\' else \'\' end,
类型 = B.name,
占用字节数 = A.Length,
长度 = COLUMNPROPERTY(A.id,A.name,\'PRECISION\'),
小数位数 = isnull(COLUMNPROPERTY(A.id,A.name,\'Scale\'),0),
允许空 = Case When A.isnullable=1 Then \'√\'Else \'\' End,
默认值 = isnull(E.Text,\'\')
FROM
syscolumns A
Left Join
systypes B
On
A.xusertype=B.xusertype
Inner Join
sysobjects D
On
A.id=D.id and D.xtype=\'U\' and D.name<>\'dtproperties\'
Left Join
syscomments E
on
A.cdefault=E.id
Left Join
sys.extended_properties G
on
A.id=G.major_id and A.colid=G.minor_id
Left Join
sys.extended_properties F
On
D.id=F.major_id and F.minor_id=0
--where d.name=\'OrderInfo\' --如果只查询指定表,加上此条件
Order By
A.id,A.colorder
/////////sql server 数据结构导出成html
Set nocount on
DECLARE @TableName nvarchar(35)
DECLARE Tbls CURSOR
FOR
Select distinct Table_name
FROM INFORMATION_SCHEMA.COLUMNS
--put any exclusions here
--where table_name not like \'%old\'
order by Table_name
OPEN Tbls
PRINT \'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\'
PRINT \'<html xmlns="http://www.w3.org/1999/xhtml">\'
PRINT \'<head>\'
PRINT \'<title>数据库字典</title>\'
PRINT \'<style type="text/css">\'
PRINT \'body{margin:0; font:11pt "arial", "微软雅黑"; cursor:default;}\'
PRINT \'.tableBox{margin:10px auto; padding:0px; width:1200px; height:auto; background:#FBF5E3; border:1px solid #45360A}\'
PRINT \'.tableBox h3 {font-size:12pt; min-height:30px; line-height:30px; background:#45360A; padding:0px 0px 0px 15px; color:#FFF; margin:0px; text-align:left }\'
PRINT \'.tableBox table {width:1200px; padding:0px }\'
PRINT \'.tableBox th {height:25px; border-top:1px solid #FFF; border-left:1px solid #FFF; background:#F7EBC8; border-right:1px solid #E0C889; border-bottom:1px solid #E0C889 }\'
PRINT \'.tableBox td {height:25px; padding-left:10px; border-top:1px solid #FFF; border-left:1px solid #FFF; border-right:1px solid #E0C889; border-bottom:1px solid #E0C889 }\'
PRINT \'</style>\'
PRINT \'</head>\'
PRINT \'<body>\'
FETCH NEXT FROM Tbls
INTO @TableName
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT \'<div class="tableBox">\'
--表说明齐全时候 可以用这个
-- Select \'<h3>表\' + @TableName +
--\' : \'+cast(Value as varchar(1000)) +
-- \'</h3>\'
-- FROM sys.extended_properties A
-- WHERE A.major_id = OBJECT_ID(@TableName)
-- and name = \'MS_Description\'
-- and minor_id = 0
--表说明不齐全的时候
print \'<h3>表\' + @TableName+\' : \'
select ISNULL(cast((select a.value
FROM sys.extended_properties A
WHERE A.major_id = OBJECT_ID( @TableName)
and name = \'MS_Description\'
and minor_id = 0) as nvarchar(100)),\'\')
print \'</h3>\'
PRINT \'<table cellspacing="0">\'
--Get the Description of the table
--Characters 1-250
PRINT \'<tr>\' --Set up the Column Headers for the Table
PRINT \'<th>字段名称</th>\'
PRINT \'<th>描述</th>\'
PRINT \'<th>主键</th>\'
PRINT \'<th>外键</th>\'
PRINT \'<th>类型</th>\'
PRINT \'<th>长度</th>\'
PRINT \'<th>数值精度</th>\'
PRINT \'<th>小数位数</th>\'
PRINT \'<th>允许为空</th>\'
PRINT \'<th>计算列</th>\'
PRINT \'<th>标识列</th>\'
PRINT \'<th>默认值</th>\'
--Get the Table Data
SELECT \'</tr><tr>\',
\'<td>\' + CAST(clmns.name AS VARCHAR(60)) + \'</td>\',
\'<td>\' + ISNULL(CAST(exprop.value AS VARCHAR(500)),\'\') + \'</td>\',
\'<td>\' + CAST(ISNULL(idxcol.index_column_id, 0)AS VARCHAR(60)) + \'</td>\',
\'<td>\' + CAST(ISNULL(
(SELECT TOP 1 1
FROM sys.foreign_key_columns AS fkclmn
WHERE fkclmn.parent_column_id = clmns.column_id
AND fkclmn.parent_object_id = clmns.object_id
), 0) AS VARCHAR(20)) + \'</td>\',
\'<td>\' + CAST(udt.name AS CHAR(15)) + \'</td>\' ,
\'<td>\' + CAST(CAST(CASE WHEN typ.name IN (N\'nchar\',N\'varchar\', N\'nvarchar\') AND clmns.max_length <> -1
THEN clmns.max_length/2
ELSE clmns.max_length END AS INT) AS VARCHAR(20)) + \'</td>\',
\'<td>\' + CAST(CAST(clmns.precision AS INT) AS VARCHAR(20)) + \'</td>\',
\'<td>\' + CAST(CAST(clmns.scale AS INT) AS VARCHAR(20)) + \'</td>\',
\'<td>\' + CAST(clmns.is_nullable AS VARCHAR(20)) + \'</td>\' ,
\'<td>\' + CAST(clmns.is_computed AS VARCHAR(20)) + \'</td>\' ,
\'<td>\' + CAST(clmns.is_identity AS VARCHAR(20)) + \'</td>\' ,
\'<td>\' + isnull(CAST(cnstr.definition AS VARCHAR(20)),\'\') + \'</td>\'
FROM sys.tables AS tbl INNER JOIN sys.all_columns AS clmns
ON clmns.object_id=tbl.object_id
LEFT OUTER JOIN sys.indexes AS idx
ON idx.object_id = clmns.object_id
AND 1 =idx.is_primary_key
LEFT OUTER JOIN sys.index_columns AS idxcol
ON idxcol.index_id = idx.index_id
AND idxcol.column_id = clmns.column_id
AND idxcol.object_id = clmns.object_id
AND 0 = idxcol.is_included_column
LEFT OUTER JOIN sys.types AS udt
ON udt.user_type_id = clmns.user_type_id
LEFT OUTER JOIN sys.types AS typ
ON typ.user_type_id = clmns.system_type_id
AND typ.user_type_id = typ.system_type_id
LEFT JOIN sys.default_constraints AS cnstr
ON cnstr.object_id=clmns.default_object_id
LEFT OUTER JOIN sys.extended_properties exprop
ON exprop.major_id = clmns.object_id
AND exprop.minor_id = clmns.column_id
-- AND exprop.name = \'MS_Description\'
WHERE (tbl.name = @TableName
--and exprop.class = 1 --这个是表注说明不可为空
) --I don\'t wand to include comments on indexes
ORDER BY clmns.column_id ASC
PRINT \'</tr></table>\'
PRINT \'</div>\'
FETCH NEXT FROM Tbls
INTO @TableName
END
PRINT \'</body></HTML>\'
CLOSE Tbls
DEALLOCATE Tbls
///oracle 查询表结构
SELECT t1.Table_Name || chr(13) || t3.comments AS "表名称及说明",
--t3.comments AS "表说明",
t1.Column_Name AS "字段名称",
t1.DATA_TYPE || \'(\' || t1.DATA_LENGTH || \')\' AS "数据类型",
t1.NullAble AS "是否为空",
t2.Comments AS "字段说明",
t1.Data_Default "默认值"
--t4.created AS "建表时间"
FROM cols t1
LEFT JOIN user_col_comments t2
ON t1.Table_name = t2.Table_name
AND t1.Column_Name = t2.Column_Name
LEFT JOIN user_tab_comments t3
ON t1.Table_name = t3.Table_name
LEFT JOIN user_objects t4
ON t1.table_name = t4.OBJECT_NAME
WHERE NOT EXISTS (SELECT t4.Object_Name
FROM User_objects t4
WHERE t4.Object_Type = \'TABLE\'
AND t4.Temporary = \'Y\'
AND t4.Object_Name = t1.Table_Name)
ORDER BY t1.Table_Name, t1.Column_ID;
///mysql 数据字典 配合Navicat Premium 12 用
select
c.TABLE_SCHEMA as \'数据库\',
c.TABLE_NAME as \'表名\',
c.COLUMN_NAME as \'字段名称\',
c.COLUMN_COMMENT as \'字段描述\',
c.COLUMN_TYPE as \'数据类型 \',
IF(kcu.ORDINAL_POSITION is not NULL,\'√\',\' \' ) AS \'主键\',
IF(c.IS_NULLABLE=\'YES\',\'√\',\' \' ) AS \'为空\',
COLUMN_COMMENT as \'取值说明\'
from information_schema.columns c
left join information_schema.key_column_usage kcu
on kcu.TABLE_SCHEMA=\'mysql\' --这个写数据库名
and c.TABLE_NAME = kcu.TABLE_NAME and c.COLUMN_NAME = kcu.COLUMN_NAME
where c.TABLE_SCHEMA=\'mysql\' --这个写数据库名
//////////////////////////////////////////////////////20190604//////////////////////////////////////////////////////////////////
oracle id 自增设置
1.设置序列
-- Create sequence
create sequence IDS7
minvalue 1
maxvalue 999999999999999999999999999
start with 1681131
increment by 1
cache 20;
2.设置函数
-- 获取序列下一个值
create or replace function get_seq_next (seq_name in varchar2) return number
is
seq_val number ;
begin
execute immediate \'select \'|| seq_name|| \'.nextval from dual\' into seq_val ;
return seq_val ;
end get_seq_next;
3.调用
select get_seq_next(\'ids7\') from dual;
//////////////////////////////////////////////////20190628*////////////////////////////////////////////////////////////////////////
select \'男\'=(select count(t.Age) from SysUser t where t.Age=1),\'女\'=(select count(a.Age) from SysUser a where a.Age=0) ; 两个查询结果放在一行;
select ep_classes, ep_name = (stuff((select \',\' + ep_name from ep_detail where ep_classes =
a.ep_classes for xml path(\'\')),1,1,\'\')) from ep_detail a group by ep_classes; 具有相同ep_classes 不同ep_name 查询结果放在一行
oracle 使用 select wm_concat(要查询内容) from test
//////////////////////////////////////////20191203
SELECT d.name, a.name , ( SELECT g.name FROM sysobjects g, syscolumns f WHERE parent_obj IN ( SELECT id FROM sysobjects WHERE name = d.name AND g.id = f.cdefault AND f.name = a.name ) ) as \'约束\' FROM syscolumns a LEFT JOIN systypes b ON a.xtype = b.xusertype INNER JOIN sysobjects d ON a.id = d.id AND d.xtype = \'U\' AND d.name <> \'dtproperties\' WHERE b.name IN (\'decimal\')
以上是关于写sql语句时候遇到的一些问题的主要内容,如果未能解决你的问题,请参考以下文章