728x90

검색 조건에 특정 기간(datetime)을 주어 조회할 경우 잠깐! 생각해 보자~!


예를 들어 2007-01-01 ~ 2007-01-10의 기간동안  가입한 회원 목록을 조회해야 한다면~
BETWEEN이나.. >= <= 를 이용하여... [ EX1 ]과 같은 방법으로 많이 한다~!


간단히 생각하믄... 맞는결과가 나올듯 하지만... 그렇지 않다.
검색필드가  datetime형식이므로  [년-월-일]은 [년-월-일 00시 00분 000초]인 셈이다.
그래서 [ EX1 ]의 방법을 이용할 경우 2007-01-10의 데이터도 조회되길 원하였으나 결과는 그렇지 못할 것이다.


그래서..[ EX2 ]처럼... 조회하였다...  훔... 허접해. 보인닷!~~~ 그러나 결과는.. 굿~!


그럼... [EX3]은??  마지막날에 +1일을 더하여 마지막날의 데이터도 포함할 수 있도록 하는것이다~..
그중에.. 이게 젤루 맘에 든다...
물론.. 2007-01-11 00:00:000 인 데이터가 존재한다면... 이건 에러다 -_-;; 
하루를 더한것에서 -1 millisecond를 빼? ㅋㅋ (생략하겠음~ -_-;;)


마지막으로.. [EX4]는 필드값을 [YYYY-MM-DD]형식으로 변형하여 조회할 수도 있겠다~

그러나 값을 변형하여.. 보여주는것도 그렇고.. 인덱스도 안걸어 놓겠지만.. 만약 있다면 인덱스 걸리지도 않을꺼구... 맘에.. 안든다..


암튼 방법이야 많겠지만... [ EX1 ]처럼... 틀린 검색 조건을 주어서는 안된다는걸.. 말하고 싶을 뿐이닷~


-- [ EX1 ]
SELECT *
FROM dbo.MEMBER
WHERE 등록일시 BETWEEN '2007-01-01' AND '2007-01-10'


-- [ EX2 ]
SELECT *
FROM dbo.MEMBER
WHERE 등록일시 BETWEEN '2007-01-01' AND '2007-01-10 59:59:999'


-- [ EX3]
SELECT *
FROM dbo.MEMBER
WHERE 등록일시 BETWEEN '2007-01-01' AND DATEADD(DAY, 1, '2007-01-10')


-- [ EX4]
SELECT *
FROM dbo.MEMBER
WHERE CONVERT(VARCHAR(10), 등록일시, 121) BETWEEN '2007-01-01' AND '2007-01-10'

728x90

-- =============================================
-- 작성일 : 2005년  03월 17일
-- 작성자 : C. H. S

-- 설   명 : 메세지를 이벤트 로그에 기록한다
-- INPUT : 사용자 정의 오류 번호, 로그에 남길 메세지

-- OUTPUT : 0 : 성공 , 1 : 실패
-- =============================================

CREATE FUNCTION dbo.UFN_LOGEVENT (@ErrNum INT, @Message VARCHAR(8000)) 
RETURNS INT AS
BEGIN
DECLARE
@RESULT INT
EXEC @RESULT = master..xp_logevent @ErrNum, @Message, WARNING
RETURN @RESULT
END


-- 실행
DECLARE @RESULT INT
EXEC @RESULT = dbo.UFN_LOGEVENT '테스트입니다'
SELECT @RESULT


-- master..xp_logevent  '사용자 정의 에러 번호', '메세지', 종류

-- WARNING 대신에 INFORMATIONAL 또는 ERROR 도 가능..

728x90

--이문장을 실행하시면 모든테이블을 대상으로 해당 command가 실행됩니다.
exec sp_MSforeachtable "exec sp_spaceused '?'"


아래 내용은 http://www.bstsoftware.com/tsug/Nov99/sp_MSforeachtable.html 에서 발췌

sp_MSforeachtable (T-SQL)

--------------------------------------------------------------------------------

Syntax

sp_MSforeachtable [@command1 =] 'sql_command'
   [, [@replacechar =] 'replacement_character']
   [, [@command2 =] 'sql_command']
   [, [@command3 =] 'sql_command']
   [, [@whereand =] 'sql_command']
   [, [@precommand =] 'sql_command']
   [, [@postcommand =] 'sql_command']

Arguments

[@command1 =] 'sql_command'     Is the sql command to apply to each user table with the
replacement_character where the table name would normally be placed. 'sql_command' is nvarchar(2000)*,
varchar(255)+ with no default. 


[, [@replacechar =] 'replacement_character']     Is the wild card character that will be replaced with each
user table name. replacement_character is char(1) with a default of '?' 


[, [@command2 =] 'sql_command']     Is the continuation of the sql command entered in @command1 to apply
to each user table with the replacement_character where the table name would normally be placed.
sql_command is nvarchar(2000)*, varchar(255)+ with a default of NULL. (Note: This parameter is not as useful
on 7.0 since there are 4000 characters available in @command1) 


[, [@command3 =] 'sql_command']     Is the continuation of the sql command entered in @command2 to apply
to each user table with the replacement_character where the table name would normally be
placed. 'sql_command' is nvarchar(2000)*, varchar(255)+ with a default of NULL. (Note: This parameter is not
as useful on 7.0 since there are 4000 characters available in @command1) 


[, [@whereand =] 'sql_command']     Is an additional where clause to limit the result set of the user table
select. sql_command is nvarchar(2000)*, varchar(255)+ with a default of NULL. No wild card replacement
occurs. It is added to the select that retrieves the user tables as passed to the procedure. It MUST be a valid
where clause for a select against sysobjects. 


[, [@precommand =] 'sql_command']     Is the sql command to be executed once before @command1 is
processed. sql_command is nvarchar(2000)*, varchar(255)+ with a default of NULL. No wild card replacement
occurs. It is executed as passed to the procedure. 


[, [@postcommand =] 'sql_command']     Is the sql command to be executed once after @command1 is
processed. sql_command is nvarchar(2000)*, varchar(255)+ with a default of NULL. No wild card replacement
occurs. It is executed as passed to the procedure. 


Return Code Values

0 (success) or @@ERROR (failure)

Result Sets

sp_MSforeachtable returns this message if no parameters are specified:

Procedure 'sp_MSforeachtable' expects parameter '@command1', which was not supplied.

Remarks

The procedure sp_MSforeachtable executes a set of commands against all the user tables in the current
database. The sp_MSforeachtable procedure executes the precommand if entered. It then declares a cursor
called hCForEach against sysobjects in the current database and passes the actual commands to be executed
to sp_MSforeach_worker. The post command is then executed if entered.

Examples

Get the number of rows in each user table

sp_MSforeachtable 'print ''?'' select count(*) from ?'

sp_MSforeachtable 'select count(*) "?" from ?'

Grant SELECT permission to the developers on every user table

EXECUTE sp_MSforeachtable 'GRANT SELECT ON ? TO Developers'

Grant all permissions to the database maintenance role on every user meta data table

EXECUTE sp_MSforeachtable @command1    = 'PRINT ''?'' GRANT SELECT , INSERT , UPDATE , DELETE
ON ? TO dbMaintenace'
                        , @whereand    = 'AND name LIKE ''tbl%REF'' ORDER BY uid , name'
                        , @precommand  = 'PRINT ''Granting permission on...'''
                        , @postcommand = 'PRINT ''Complete!'''


+ Recent posts