Some common sql statement

1, create a table
2, an additional field - Delete field
3, a random number
4, the time to String
5, the query year, month, day
6, Case, the When, the Then
7, acquisition of new Sql Id
8, increase the number
9, the try-the Catch
10, time-related sql query
11, query sql execution time and CPU utilization time and I / O operations case
12, alternatively
13, drop the table empty table, copy sheet
14, clean up the log
15, the lock-table queries, unlock
16, Sql statement performance Top10 
17, information look-up table
18, a lookup table instructions
19, lookup table fields details
ok! ! !
1, create a table
- drop table
--DROP TABLE [dbo] [table name].

--创建表
CREATE TABLE [dbo].[System_Code_InstallationPeriod] (
[Id] INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
[Name] nvarchar(50) NULL DEFAULT '默认值',
[TypeId] INT NULL,
[Money] money NULL,
[CreatePeople] nvarchar(50) NULL ,
[CreateTime] datetime NULL ,
[ModifyPeople] nvarchar(50) NULL ,
[ModifyTime] datetime NULL
)

- Add table shows
EXECUTE sp_addextendedproperty N'MS_Description ', N' installation time table ', N'user', N'dbo ', N'table', N '[ table name]', NULL, NULL
- delete table shows
--EXEC sp_dropextendedproperty N'MS_Description ',' user ' ,' dbo ',' table ',' [ table name] ', NULL, NULL

- Add Field Description
EXECUTE sp_addextendedproperty N'MS_Description ', N' create [people] ', N'user', N'dbo ', N'table', N '[ table name]', N'column ', N' [field name] '
the EXECUTE sp_addextendedproperty N'MS_Description', N '] [created time', N'user ', N'dbo', N'table ', N' [ table name] ', N'column', N ' [field name] '
the EXECUTE sp_addextendedproperty N'MS_Description', N '[Modifier]', N'user ', N'dbo', N'table ', N' [ table name] ', N'column', N ' [field name] '
the EXECUTE sp_addextendedproperty N'MS_Description', N '] [modified', N'user ', N'dbo', N'table ', N' [ table name] ', N'column', N ' [field name] '

- Delete Field Description
--EXEC sp_dropextendedproperty N'MS_Description ',' user ' ,' dbo ',' table ',' table ',' column ',' field name '

2, additional fields - Delete field
- add a field
alter table [table] the ADD [Field Name] the INT NULL;
alter table [table] the ADD [field name] nvarchar (50) NULL;

- Add Field Description
EXECUTE sp_addextendedproperty N'MS_Description ', N' [Name] ', N'user', N'dbo ', N'table', [ table name] ', N'column', [field name] ';
the EXECUTE sp_addextendedproperty N'MS_Description', N '[name]', N'user ', N'dbo', N'table ', [ table name]', N'column ', [field name]';

- Delete field
ALTER TABLE [table] DROP COLUMN [field name]
3, a random number
the SELECT LTRIM (Floor (RAND () * 10000))
. 4, the time switch string
--2018-11-13
the SELECT the CONVERT (VARCHAR ( 50), GETDATE (), 23 ) AS 'TIME'

--2018-11-13 18:46:14
SELECT CONVERT(varchar(50) , GETDATE(), 20 ) AS 'TIME'

17 --2019-01-14: 15: 59.920
the SELECT Convert For (VARCHAR (50), GETDATE (), 121)
5, the query year, month, day
the SELECT
CONVERT (VARCHAR (4), YEAR (GETDATE ())) AS 'in',
CONVERT (VARCHAR (4), mONTH (GETDATE ())) AS 'month',
CONVERT (VARCHAR (4), dAY (GETDATE ())) AS 'day'
6, Case, the When, the Then
the SELECT
the CASE sex
the WHEN 0 THEN 'F'
the WHEN. 1 THEN 'M'
the ELSE ''
the END the AS 'sex'
the FROM
[table]

The SELECT
the CASE
the WHEN w_grade> = 90 THEN'A '
the WHEN w_grade> the AND w_grade = 80 <= 89 THEN' B '
the WHEN w_grade> the AND w_grade = 70 <= 79 THEN' C '
the WHEN w_grade> the AND w_grade = 60 <= 69 THEN 'D'
ELSE 'E'
financial knowledge www.gendan5.com/topic/businessnews.html
END AS 'Grading'
the FROM
[table name]
7, to obtain a new Sql Id
the SELECT @@ IDENTITY - get is a cross-domain The latest id

SELECT IDENT_CURRENT ( '[table name]') - have the current id specified table

SELECT SCOPE_IDENTITY () - is obtained in the current database id of the last inserted table
8, increasing number
SELECT row_number () OVER (ORDER BY Id) AS ' number', * FROM [dbo] [table].
. 9, the Try -catch
the BEGIN TRY
the SELECT. 5/0
the END TRY
the BEGIN the CATCH
the SELECT ERROR_MESSAGE () the AS "error description",
ERROR_NUMBER () the AS "error number",
ERROR_SEVERITY () the AS 'severity',
ERROR_STATE () the AS 'error state number'
ERROR_LINE () AS 'error line number',
ERROR_PROCEDURE () the AS 'error occurs stored procedure or trigger name'
the END the CATCH
10, time-related query Sql
--20,190,306,094,000
SELECT Convert (VARCHAR (. 8), GETDATE ( ), 112) + replace (convert (varchar (8), GETDATE (), 114), ':', '')

--20190306094332437
select convert(varchar(8),GETDATE(),112)+replace(convert(varchar(12),GETDATE(),14),':','')

--当月天数
select day(dateadd(ms,-3,DATEADD(m, DATEDIFF(m,0,getdate())+1,0)))

--- first of the month
select dateadd (d, -day (getdate ()) + 1, getdate ())

--- the last day of the month
select dateadd (d, -day (getdate ()), dateadd (m, 1, getdate ()))

- the last day of the next year month at this time
select dateadd (d, -day (getdate ()), dateadd (m, 12, getdate ()))

- the first Monday of the month
SELECT DATEADD (wk, DATEDIFF (wk , '', DATEADD (dd, 6 - DAY (getdate ()), getdate ())), '')

- Today, all the data
select * from [table] where DateDiff (dd, CreateTime, getdate ()) = 0

- yesterday all the data
select * from [table] where DateDiff (dd, CreateTime, getdate ()) = 1

All data --7 days
select * from [table] where DateDiff (dd, CreateTime, getdate ()) <= 7

All data --30 days
select * from [table] where DateDiff (dd, CreateTime, getdate ()) <= 30

- All month data:
SELECT * from [table] where DateDiff (mm, CreateTime, getdate ()) = 0

- All year data
select * from [table] where DateDiff (yy, CreateTime, getdate ()) = 0

- Query Today is the day of this year's
select datepart (dayofyear, getDate () )

- Query Today is the day of the month
the SELECT the datepart of a (dd, getDate ())
the SELECT Day (getDate ())

- This week's Monday date query is how much (note: not specified date is Sunday, if Sunday will be calculated until Monday to Sunday so if you want to cut one day.)
The SELECT DATEADD (wk, DATEDIFF (wk, 0, getdate ()), 0 )

- Query yesterday Date
select convert (char, dateadd (DD , -1, getdate ()), 121)

- Query first day of the month date
Select DATEADD (mm, DATEDIFF (mm , 0, getdate ()), 0) as firstday

- Query the last day of the month date
Select dateadd (ms, -3, DATEADD (mm, DATEDIFF (m, 0, getdate ()) + 1, 0)) as lastday

--本月有多少天
select datepart(dd,dateadd(dd,-1,dateadd(mm,1,cast((cast(year(getdate()) as varchar)+'-'+cast(month(getdate()) as varchar)+'-01' ) as datetime ))))

- the sum of two time periods differ several days
select datediff (day, '2016/ 5/17', '2016/8/20') as daysum

- on the specified date in days ± N
select convert (char, dateadd (dd , 1, getdate ()), 111) as riqi

- on the specified date ± N min: // check the current time of 15 minutes before date
SELECT DATEADD (mi The, -15, getdate ())
. 11, sql query execution time and CPU utilization time and I / O operating conditions
- - View the execution time and cpu usage time

set statistics time on
select * from [表名]
set statistics time off

- View query case of I / 0's

SET statistics IO ON
SELECT from [table]
SET statistics IO OFF
12 is, replace
the UPDATE [table] the SET [field] = replace ([field], 'replace the first content', 'replace the contents');
13, delete the table , empty table, copy table
DROP tABLE table name - delete table
TRUNCATE tABLE table name - empty data table
the SELECT
INTO target table names from the source table
14, clean up log
the USE [Master]
GO
the ALTER dATABASE want to clean up the database name the RECOVERY the sIMPLE the WITH NO_WAIT the sET
the GO
the ALTER dATABASE database name to be cleaned sET RECOVERY sIMPLE - simple mode
the GO
the USE database name to be cleaned
the GO
the DBCC SHRINKFILE (N 'database name to be cleaned _log', 2, TRUNCATEONLY) - compression set after the log size 2M, you can specify self-
GO
the USE [Master]
GO
database name ALTER dATABASE want to clean up the WITH FULL NO_WAIT the RECOVERY the SET
GO
ALTER DATABASE to clean up the database name SET RECOVERY FULL - revert to full mode
GO
15, the lock-table query, unlocking
- see table was locked:
the SELECT
request_session_id SPID,
OBJECT_NAME (resource_associated_entity_id) tableName
the FROM
the sys.dm_tran_locks
the WHERE
resource_type = 'the OBJECT'
ORDER BY request_session_id ASC

- Unlock:
the DECLARE the INT @spid
the SET 52 is @spid = - process table lock
the DECLARE @SQL VARCHAR (1000)
the SET @SQL = 'the kill' the CAST + (@spid the AS VARCHAR)
EXEC (@SQL)
16, the Sql statement performance TOPlO 
the SELECT the TOP 10
st.text the AS [parent complete statement],
the SUBSTRING (st.text, (qs.statement_start_offset / 2) +. 1, ((the CASE statement_end_offset the WHEN -1 THEN the DATALENGTH (st.text) the ELSE qs.statement_end_offset the END - qs.statement_start_offset) / 2) + 1 ) as [ statistical statement corresponding portion],
the CAST (((qs.total_elapsed_time / 1000000.0) /qs.execution_count) the AS DECIMAL (28,2)) the AS [average consumption seconds] ,
the CAST (qs.last_elapsed_time / 1000000.0 the AS DECIMAL (28, 2)) the AS [finalize consumption seconds],
qs.last_execution_time the AS [last execution time],
the CAST (qs.min_elapsed_time / 1000000.0 the AS DECIMAL (28, 2)) the AS [minimum consumption seconds],
CAST (qs.max_elapsed_time / 1000000.0 AS DECIMAL ( 28, 2)) AS [ maximum consumption seconds],
the CAST (qs.total_elapsed_time / 1,000,000.0 the AS DECIMAL (28, 2)) the AS [total consumed seconds],
(qs.execution_count ) AS [total number of executions],
[compile time program] CREATION_TIME AS,
CAST (qs.last_worker_time / 1000000.0 AS DECIMAL (28, 2)) AS [to finalize the number of seconds of CPU]
from sys.dm_exec_query_stats QS
the CROSS APPLY SYS. dm_exec_sql_text (qs.sql_handle) the AS ST
the CROSS the APPLY the sys.dm_exec_query_plan (qs.plan_handle) QP
the WHERE qs.last_execution_time> the DATEADD (n-, -30, GETDATE ())
the ORDER BY DESC qs.last_worker_time
. 17, table information query
SELECT
table name = case when a.colorder = 1 then d.name else '' end,
table illustrates = case when a.colorder = 1 then isnull (f.value, '') else '' end,
the field number = a.colorder,
field name = a.name,
标识=case when COLUMNPROPERTY( a.id,a.name,'IsIdentity')=1 then '√'else '' end,
主键=case when exists(SELECT 1 FROM sysobjects where xtype='PK' 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,''),
字段说明=isnull(g.[value],'')
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'
E ON a.cdefault the Join the syscomments left = e.id
left the Join sys.extended_properties G = ON a.id g.major_id and a.colid = g.minor_id
left ON d.id the Join sys.extended_properties F and F = f.major_id = 0 .minor_id
--where d.name = '[table name] "- if only the specified table query, coupled with the condition
Order by a.id, a.colorder
18 is, described look-up table

SELECT
table name = d.name,
table illustrates = isnull (. F VALUE, ' '),
the table query = 'SELECT the TOP 10 the FROM' + + d.name ';',
table shows = '-' + CONVERT (varchar ( 100), ISNULL (F. of VALUE, ''))
the FROM
the sysobjects D
the LEFT the JOIN sys.extended_properties the ON d.id F = f.major_id
the AND f.minor_id = 0
the WHERE
d.xtype = 'the U-'
the AND d.name <> 'the dtproperties'
--and d.name like '% [table name]%' - if only the specified table query, add this condition
the ORDER BY d.name
19, lookup table fields details
SELECT
table name = case when a.colorder = 1 then d.name else '' end ,
table illustrates = case when a.colorder = 1 then isnull (f.value, '') else '' end,
field name 1 = a.name,
字段名5=(SELECT STUFF((SELECT ',' + a.Name FROM syscolumns AS a INNER JOIN sysobjects d ON a.id = d.id AND d.xtype = 'U' AND d.name <> 'dtproperties' where d.name='[表名]' FOR XML PATH ('')),1,1,'')),
字段名6=(SELECT STUFF((SELECT ',@' + a.Name FROM syscolumns AS a INNER JOIN sysobjects d ON a.id = d.id AND d.xtype = 'U' AND d.name <> 'dtproperties' where d.name='[表名]' FOR XML PATH ('')),1,1,'')),
字段名7=(SELECT STUFF((SELECT ','+ CASE
WHEN b.name = 'nvarchar' THEN 'string'
WHEN b.name = 'int' THEN 'int'
WHEN b.name = 'datetime' THEN 'DateTime'
ELSE 'decimal?'
END +' ' + a.Name FROM syscolumns AS 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' where d.name='[表名]' FOR XML PATH ('')),1,1,'')),
字段名8='new SqlParameter("@'+a.name+'", '+a.name+'),',
字段名9=case
when b.name = 'nvarchar' then '/// <summary>
///'+ isnull(CONVERT(varchar(100),g.[value]),'')+'
/// </summary>
public string '+a.name+' { get; set; }'
when b.name = 'int' then'/// <summary>
/// '+ isnull(CONVERT(varchar(100),g.[value]),'')+'
/// </summary>
public int '+a.name+' { get; set; }'
when b.name = 'datetime' then'/// <summary>
/// '+ isnull(CONVERT(varchar(100),g.[value]),'')+'
/// </summary>
public DateTime '+a.name+' { get; set; }'
else '/// <summary>
/// '+ isnull(CONVERT(varchar(100),g.[value]),'')+'
/// </summary>
public decimal? '+a.name+' { get; set; }' end,
类型 = case when b.name = 'nvarchar' then b.name +'('+ CONVERT(varchar(50),COLUMNPROPERTY(a.id,a.name,'PRECISION'))+'),' else b.name+',' end,
字段说明1= case when (isnull(CONVERT(varchar(100),g.[value]),'')) ='' then '' else ('--' + isnull(CONVERT(varchar(100),g.[value]),'')) end,
字段说明2= case when (isnull(CONVERT(varchar(100),g.[value]),'')) ='' then '' else ('/
' + isnull(CONVERT(varchar(100),g.[value]),'') + '*/') end,
字段说明3= case when (isnull(CONVERT(varchar(100),g.[value]),'')) ='' then '' else ('//' + isnull(CONVERT(varchar(100),g.[value]),'')) end
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='[表名]'
order by a.id,a.colorder

Guess you like

Origin blog.51cto.com/14513127/2478096