--변수 생성--declare 변수명 타입DECLARE @name varchar(20)
--변수에 값 할당SET @name = 'Kendrick'--혹은--userid가 sonim1일 때 이름이 Kendrick일 경우 SELECT @name = P.name FROM tblPerson P WHERE userid = 'sonim1'
SET을 하던 SELECT를 하던 동일한 값이 @name 변수에 할당되는 쿼리입니다.
아래는 @name 변수를 이용해서 이어서 해당 user의 가입일을 알아보겠습니다.
SELECT CreateDate -- 생성일 필드FROM tblPerson P
WHERE P.name = @name
이정도면 변수의 사용법은 충분히 이해되실것 입니다.
테이블 변수
이제 알아볼 항목은 테이블 변수입니다. 변수에서는 값뿐이 아니라 여러행으로 떨어지는 결과를 담아 둘 수 있습니다.
예를 보 시죠
--테이블 변수 생성, 자료형 대신에 테이블 스키마가 들어가 있다.DECLARE @userData TABLE(
name varchar(30) NOTNULL,
CreateDate datetime NOTNULL
);
--Insert Into Select 문을 이용하여 k로 시작하는 회원의 리스트를 할당해보자INSERTINTO @userData
SELECT name, CreateDate
FROM tblPerson
WHERE name like'k%'--할당 후에는 변수를 이용하여 테이블처럼 사용가능하다.SELECT * FROM @userData
변수와 테이블 변수에 대해서 간단하게 알아보았습니다. 테이블 변수를 이용하여 쿼리의 복잡성을 떨어트릴수 있으며, 속도 개선에 많은 도움이 될 것입니다.
테이블 변수와 임시 테이블의 차이점
임시테이블
테이블 변수
존재 기간
명시적으로 삭제를 안할 시에는 세션 연결 기간동안 존재
명시적으로 삭제를 안할 시에는 배치 처리기간 동안 존재
저장소
Tempdb
Tempdb
쿼리비용
대용량에서는 쿼리 비용 유리
소용량에서 쿼리 비용 유리
장단점
대용량 데이터 처리에 유리
소용량 데이터 처리에서 유리
세션 단위 처리시에 사용
저장 프로시져에서 테이블 변수 사용하면 임시 테이블 사용할 떄보다 저장 프로시저를 다시 컴파일하는 일이 줄어듦
배치 처리 단위인 저장 프로시져에서 사용 유리
마치며
잘못 사용하면 성능상 문제가 있겠지만 잘 사용하면 너무나 유용한 기능입니다. 물론 말은 쉽습니다. 하하 사실 잘못 사용하기가 더 어려운 기능이겠네요. !! 좋은 하루 되세요
당시 산업혁명 직후 아메리카 드림등 노동과 성공에만 관심을 쏟던 세태와 달리 직접 숲에서 집을 만들고 혼자서 자립해서 살았다. 당연히 당시 사람들에겐 외면을 받았지만 계속된 노동과 반복에 질린 현대인들에게 월든이 힘이 되어주면서 현대에 와서야 비로소 빛을 바라보기 시작했다.
실천적 초월주의자인 소로우는 미국적 삶의 주류에 정면으로 반기를 든 실험적 삶을 산 사람이었다. 하지만, 당대 생활양식의 비판 근거를 미국적 이념에서 찾았기에 그는 미국적 특성이 강한 작가라고도 여겨진다. 산업화와 근대화에 사로잡힌 근대적인 삶의 양식을 거부하고 비판한 그는 내면의 풍요로움, 검소한 삶, 자급자족의 삶을 강조하였다. 이외에도, 그는 자연친화적인 삶을 중시하고 전쟁과 노예제도를 비롯한 물질문명과 인간의 이기와 탐욕을 싫어하고 반대하며 옳지 못한 정부와 사회에 대해선 합법적이면서도 간접, 소극적으로라도 반대, 저항하고 맞설 것을 주장하는 시민 불복종 운동을 주장한 생태주의자였다.
그렇긴 한데, 1844년 4월경 피시 차우더 수프를 만들던 중 콩코드의 숲 300 에이커(약 1,200,000m2)를 태워먹은 적이 있다.
폴아웃 4 - 시대가 2270년도이다 보니 당연히 직접 등장하진 않지만 배경이 콩코드라서 작중에서 소로가 살았던 오두막이 등장한다. 핵폭탄이 떨어졌음에도 오두막은 살아남았다. 오두막 근처 스피커로 소로에 대한 간략한 소개를 들을 수도 있으니, 관심있다면 듣는 것도 좋다. 다만 전쟁 전에 이미 그의 오두막은 기념품 상점으로 변했었고, 호수는 물이 상당히 마른데다 쓰레기도 많이 있으며 지하 땅굴에는 작중의 도적패인 레이더(폴아웃 시리즈)도 살고 있다. 동료 중 하나인 코즈워스는 '핵전쟁이 지나고 나서야 우리가 소박한 삶을 되찾게 되리란걸 소로는 생각조차 못했을 것 이다.'라고 씁쓸한 한마디를 한다. 그 외의 동료들도 한마디 씩은 하는데, 퀴리(폴아웃 4)와 파이퍼 라이트, 닉 발렌타인 등 선 성향은 대체적으로 긍정적인 말을 하지만 악 성향은 비꼬거나 비웃는 말을 한다. 가장 백미는 팔라딘 댄스의 '나 이 작가 알어. 숲속으로 살아남기인가 하는 책 쓴 사람 아냐?'(...)
[1] 월든의 대사. 평론가 이동진이 영화 문라이트의 평에서 인용하기도 했다.[2] 주변인의 권유로 소로가 처음 낸 책인데 말그대로 폭망해버려 소로가 남은 책을 다 사야만했다
로크가 《통치론》에서 제시한 사회계약 원리들 중 백미는 무엇보다 국민의 저항권을 인정한 데 있다. 로크가 《통치론》을 저술한 실질적인 목적은 저항권의 정당성을 입증하는 데 있었다. 저항권이란 정부가 처음 만들어질 당시의 목적을 제대로 수행하지 않는다면, 즉 구성원의 생명과 재산, 자유를 보호하지 않는다면 무력을 사용해서라도 저항할 수 있다는 논리다. 당시 전제 군주가 무소불위의 권력을 휘두르고, 그의 권력에 대한 도전은 신성모독죄로 간주되던 시대에 대범하게도 로크는 국민의 저항을 권리로서 인정했던 것이다.
홉스와 마찬가지로 로크 역시 인간의 자연상태를 전제로 자신의 사회계약 논의를 전개한다. 그러나 로크가 보기에 ‘만인의 만인에 대한 투쟁’과 같은 홉스의 자연상태를 보는 가정에는 난점을 가지고 있다. 왜냐하면 합리적인 이기주의자가 자연상태에서 계약하는 이유는 계약을 통해 자기 자신 특히 자신의 생명과 자유와 재산을 더 잘 보호하려는 의도에서라는 것이다. 그런데 자연상태에서 누리던 평등을 포기하고 절대 군주의 지배 아래 예속된다는 홉스의 추론은 합리성의 관점에서 볼 때 설득력이 떨어진다. 왜냐하면 자신의 처지가 더 나빠지는 계약에 합의하는 합리적인 존재는 생각하기 어렵기 때문이다.
군주도 이기적인 인간일 뿐
로크가 보기에 홉스의 추론은 논리적 일관성이 없다. 로크에 의하면 홉스의 사회계약이란 사회 구성원 간에 성립하는 것으로서 그 속에 군주는 포함되지 않는다. 그러나 군주도 하나의 이기적인 인간에 불과하다. 이러한 군주가 재판관이 되고 군주가 임의로 사람들을 해친다면 이는 오히려 자연상태보다 못한 상황이 된다. 이와 같은 절대 군주제 아래에서 살아간다는 것은 말하자면 자연상태 속의 여우를 피하려다가 오히려 사자에게 잡아먹히는 것과 다를 바 없다. 이 경우 군주와 사회 구성원의 관계는 여전히 자연상태에 있게 돼 전쟁이 계속된다는 문제가 있다.
따라서 홉스의 사회계약설에서는 군주의 이기심 문제를 해결하기 위해 군주와 사회 구성원 간에 다시 하나의 계약이 요청된다. 그런데 그렇게 되면 이 계약 이행을 보장하기 위해 계약을 감시할 더 높은 또 다른 하나의 군주가 필요하게 된다. 문제는 이러한 과정은 무한정 계속돼야 한다. 따라서 홉스의 사회계약 추론은 무한소급의 오류에 빠진다.
이러한 난점을 피하기 위해 로크는 자연상태를 자유롭고 평등한 상태라고 가정한다. 자연상태가 이처럼 평화롭고 목가적이라면 홉스와 달리 로크에게 있어서 사람들이 계약을 통해 국가나 정부를 수립하는 합리적인 이유는 무엇인가? 로크에 의하면 자연상태의 질서가 갖는 불완전성 때문이다. 즉 사람들이 저마다 자신의 행위가 옳다고 주장할 경우 자연상태에서는 이를 중재할 재판관이 없기 때문에 모두가 불안한 상태에서 지내야만 한다는 것이다. 이를 해소하기 위해 정치 공동체인 정부를 만들 수밖에 없으며, 이때 자신의 권리를 대리자인 정부에 일부 양도하기로 계약을 맺는다. 여기서 양도의 대상이 되는 권리는 ‘소유권’을 지키기 위한 이차적 권리인 ‘처벌권’이다. 원래의 권리인 소유권은 전혀 양도되지 않는다.
홉스의 계약설 문제 해소
이렇게 보면 로크는 통치권을 절대 군주로부터 국민에게로 옮김으로써 홉스의 사회계약설이 안고 있는 문제를 해결하고자 했다. 이제 로크에게 있어서 정부는 더 이상 통치자가 아니다. 정부는 사람들의 소유권을 보호하기 위해 부분적으로 양도받은 권한을 갖고 있는 국민의 대리자로서 의미를 갖는다. 권력의 주인은 국민이므로 국민은 통치받는 사람인 동시에 통치자가 된다.
절대왕정 시기 로크의 사회계약 사상은 가히 혁명적이었으며, 명예혁명 이전 로크의 《통치론》은 당연하게도 불온서적으로 지정됐다. 그러나 《통치론》의 내용들은 프랑스에 전해져 프랑스 혁명을 일으키는 도화선이 됐으며, 미국에 전해져 미국 혁명을 정당화하는 이론적 도구가 됐다. 절대 권력에서 사람들이 해방된 것이 그리 오래전 일이 아니란 점에서 오늘날 우리가 향유하는 모든 자유와 권리는 공기처럼 당연한 것이 아니라는 것을 다시 생각하게 된다.
◆기억해주세요
<통치론>의 내용들은 프랑스에 전해져 프랑스 혁명을 일으키는 도화선이 됐으며, 미국에 전해져 미국 혁명을 정당화하는 이론적 도구가 됐다.
모든 시스템 날짜 및 시간 값은 SQL Server 인스턴스가 실행 중인 컴퓨터 운영 체제에서 가져옵니다.
정밀도가 높은 시스템 날짜 및 시간 함수
SQL Server 2017GetSystemTimeAsFileTime() Windows API를 사용 하 여 날짜 및 시간 값을 가져옵니다.정확도는 SQL Server 인스턴스가 실행되고 있는 컴퓨터의 하드웨어와 Windows 버전에 따라 달라집니다.이 API의 정밀도는 100나노초로 고정됩니다.GetSystemTimeAdjustment() Windows API를 사용 하 여 정확도 확인할 수 있습니다.
Repeats a group of statements a specified number of times.
Syntax
For counter [ As datatype ] = start To end [ Step step ]
[ statements ]
[ Continue For ]
[ statements ]
[ Exit For ]
[ statements ]
Next [ counter ]
Parts
Part
Description
counter
Required in theForstatement. Numeric variable. The control variable for the loop. For more information, seeCounter Argumentlater in this topic.
datatype
Optional. Data type ofcounter. For more information, seeCounter Argumentlater in this topic.
start
Required. Numeric expression. The initial value ofcounter.
end
Required. Numeric expression. The final value ofcounter.
step
Optional. Numeric expression. The amount by whichcounteris incremented each time through the loop.
statements
Optional. One or more statements betweenForandNextthat run the specified number of times.
Continue For
Optional. Transfers control to the next loop iteration.
Exit For
Optional. Transfers control out of theForloop.
Next
Required. Terminates the definition of theForloop.
Note
TheTokeyword is used in this statement to specify the range for the counter. You can also use this keyword in theSelect...Case Statementand in array declarations. For more information about array declarations, seeDim Statement.
Simple Examples
You use aFor...Nextstructure when you want to repeat a set of statements a set number of times.
In the following example, theindexvariable starts with a value of 1 and is incremented with each iteration of the loop, ending after the value ofindexreaches 5.
VB
For index AsInteger = 1To5
Debug.Write(index.ToString & " ")
Next
Debug.WriteLine("")
' Output: 1 2 3 4 5
In the following example, thenumbervariable starts at 2 and is reduced by 0.25 on each iteration of the loop, ending after the value ofnumberreaches 0. TheStepargument of-.25reduces the value by 0.25 on each iteration of the loop.
VB
For number AsDouble = 2To0Step-0.25
Debug.Write(number.ToString & " ")
Next
Debug.WriteLine("")
' Output: 2 1.75 1.5 1.25 1 0.75 0.5 0.25 0
Tip
AWhile...End While StatementorDo...Loop Statementworks well when you don't know in advance how many times to run the statements in the loop. However, when you expect to run the loop a specific number of times, aFor...Nextloop is a better choice. You determine the number of iterations when you first enter the loop.
Nesting Loops
You can nestForloops by putting one loop within another. The following example demonstrates nestedFor...Nextstructures that have different step values. The outer loop creates a string for every iteration of the loop. The inner loop decrements a loop counter variable for every iteration of the loop.
VB
For indexA = 1To3' Create a new StringBuilder, which is used' to efficiently build strings.Dim sb AsNew System.Text.StringBuilder()
' Append to the StringBuilder every third number' from 20 to 1 descending.For indexB = 20To1Step-3
sb.Append(indexB.ToString)
sb.Append(" ")
Next indexB
' Display the line.
Debug.WriteLine(sb.ToString)
Next indexA
' Output:' 20 17 14 11 8 5 2' 20 17 14 11 8 5 2' 20 17 14 11 8 5 2
When nesting loops, each loop must have a uniquecountervariable.
You can also nest different kinds control structures within each other. For more information, seeNested Control Structures.
Exit For and Continue For
TheExit Forstatement immediately exits theFor…Nextloop and transfers control to the statement that follows theNextstatement.
TheContinue Forstatement transfers control immediately to the next iteration of the loop. For more information, seeContinue Statement.
The following example illustrates the use of theContinue ForandExit Forstatements.
VB
For index AsInteger = 1To100000' If index is between 5 and 7, continue' with the next iteration.If index >= 5And index <= 8ThenContinueForEndIf' Display the index.
Debug.Write(index.ToString & " ")
' If index is 10, exit the loop.If index = 10ThenExitForEndIfNext
Debug.WriteLine("")
' Output: 1 2 3 4 9 10
You can put any number ofExit Forstatements in aFor…Nextloop. When used within nestedFor…Nextloops,Exit Forexits the innermost loop and transfers control to the next higher level of nesting.
Exit Foris often used after you evaluate some condition (for example, in anIf...Then...Elsestructure). You might want to useExit Forfor the following conditions:
Continuing to iterate is unnecessary or impossible. An erroneous value or a termination request might create this condition.
ATry...Catch...Finallystatement catches an exception. You might useExit Forat the end of theFinallyblock.
You have an endless loop, which is a loop that could run a large or even infinite number of times. If you detect such a condition, you can useExit Forto escape the loop. For more information, seeDo...Loop Statement.
Technical Implementation
When aFor...Nextloop starts, Visual Basic evaluatesstart,end, andstep. Visual Basic evaluates these values only at this time and then assignsstarttocounter. Before the statement block runs, Visual Basic comparescountertoend. Ifcounteris already larger than theendvalue (or smaller ifstepis negative), theForloop ends and control passes to the statement that follows theNextstatement. Otherwise, the statement block runs.
Each time Visual Basic encounters theNextstatement, it incrementscounterbystepand returns to theForstatement. Again it comparescountertoend, and again it either runs the block or exits the loop, depending on the result. This process continues untilcounterpassesendor anExit Forstatement is encountered.
The loop doesn't stop untilcounterhas passedend. Ifcounteris equal toend, the loop continues. The comparison that determines whether to run the block iscounter<=endifstepis positive andcounter>=endifstepis negative.
If you change the value ofcounterwhile inside a loop, your code might be more difficult to read and debug. Changing the value ofstart,end, orstepdoesn't affect the iteration values that were determined when the loop was first entered.
If you nest loops, the compiler signals an error if it encounters theNextstatement of an outer nesting level before theNextstatement of an inner level. However, the compiler can detect this overlapping error only if you specifycounterin everyNextstatement.
Step Argument
The value ofstepcan be either positive or negative. This parameter determines loop processing according to the following table:
Step value
Loop executes if
Positive or zero
counter<=end
Negative
counter>=end
The default value ofstepis 1.
Counter Argument
The following table indicates whethercounterdefines a new local variable that’s scoped to the entireFor…Nextloop. This determination depends on whetherdatatypeis present and whethercounteris already defined.
Isdatatypepresent?
Iscounteralready defined?
Result (whethercounterdefines a new local variable that’s scoped to the entireFor...Nextloop)
No
Yes
No, becausecounteris already defined. If the scope ofcounterisn't local to the procedure, a compile-time warning occurs.
Yes, but only if the existingcountervariable is defined outside the procedure. That variable remains separate. If the scope of the existingcountervariable is local to the procedure, a compile-time error occurs.
Yes
No
Yes.
The data type ofcounterdetermines the type of the iteration, which must be one of the following types:
An enumeration that you declare by using anEnum Statement.
AnObject.
A typeTthat has the following operators, whereBis a type that can be used in aBooleanexpression.
Public Shared Operator >= (op1 As T, op2 As T) As B
Public Shared Operator <= (op1 As T, op2 As T) As B
Public Shared Operator - (op1 As T, op2 As T) As T
Public Shared Operator + (op1 As T, op2 As T) As T
You can optionally specify thecountervariable in theNextstatement. This syntax improves the readability of your program, especially if you have nestedForloops. You must specify the variable that appears in the correspondingForstatement.
Thestart,end, andstepexpressions can evaluate to any data type that widens to the type ofcounter. If you use a user-defined type forcounter, you might have to define theCTypeconversion operator to convert the types ofstart,end, orstepto the type ofcounter.