常用SQL语句
1. COALESCE: 该函数会返回参数中第一个非NULL的值
SELECT COALESCE(NULL,'col2','col1') -- This clause will return 'col2', you can change the order of parameters,you will be understand.
2. sp_configure: 这个sp在你使用OPENROWSET的时候你可能会用到.与些命令相关的就是RECONFIGURE.
exec sp_configure 'show advanced options', 1 -- This clause will show you advanced options when you run sp_configure
reconfigure -- Do not forget to run this command
P.S: 下面2点关于使用OPENROWSET的时候要注意的:
a.OPENROWSET必须要运行在sql的服务器上,如果运行在client上就会报错.
b.要运行 exec sp_configure 'Ad Hoc Distributed Queries', 1
3. 获取时间的小时部分:
SELECT DATEPART(HOUR,'2010-07-19 01:00:00.000')
4. 时间的相加 or 相减:
SELECT DATEDIFF(HOUR,'2010-07-19 00:00:00.000','2010-07-19 01:00:00.000');
SELECT DATEADD(HOUR,1,'2010-07-19 00:00:00.000');
SELECT DATEADD(HOUR,1,'2010-07-19 00:00:00.000');
5. 保留小数的问题:
SELECT CAST(ROUND(5/(3*1.0),3) AS NUMERIC(9,3))
6. 关于Sql Server中log的记录.
创建Log表:
代码
-- Author: Sandals
-- Date : 2010-08-09 21:00:00
IF EXISTS(SELECT [name] FROM sys.tables WHERE [name] = 'ErrorLog')
DROP TABLE [dbo].[ErrorLog];
GO
CREATE TABLE [dbo].[ErrorLog](
[LogId] [int] IDENTITY(1,1) NOT NULL,
[ErrorNumber] [int] NULL DEFAULT ERROR_NUMBER(),
[ErrorState] [int] NULL DEFAULT ERROR_STATE(),
[ErrorLine] [int] NULL DEFAULT ERROR_LINE(),
[ErrorProcedure] [nvarchar](100) DEFAULT ERROR_PROCEDURE()NULL,
[ErrorMessage] [nvarchar](4000) DEFAULT ERROR_MESSAGE() NULL
)
GO
-- Date : 2010-08-09 21:00:00
IF EXISTS(SELECT [name] FROM sys.tables WHERE [name] = 'ErrorLog')
DROP TABLE [dbo].[ErrorLog];
GO
CREATE TABLE [dbo].[ErrorLog](
[LogId] [int] IDENTITY(1,1) NOT NULL,
[ErrorNumber] [int] NULL DEFAULT ERROR_NUMBER(),
[ErrorState] [int] NULL DEFAULT ERROR_STATE(),
[ErrorLine] [int] NULL DEFAULT ERROR_LINE(),
[ErrorProcedure] [nvarchar](100) DEFAULT ERROR_PROCEDURE()NULL,
[ErrorMessage] [nvarchar](4000) DEFAULT ERROR_MESSAGE() NULL
)
GO
插入Log到表中:
BEGIN TRY
SELECT 1/0
END TRY
BEGIN CATCH
INSERT INTO dbo.ErrorLog DEFAULT VALUES
END CATCH
SELECT 1/0
END TRY
BEGIN CATCH
INSERT INTO dbo.ErrorLog DEFAULT VALUES
END CATCH
7. 获取当前数据库文件的大小。
SELECT * FROM SYS.SYSFILES


浙公网安备 33010602011771号