2016-07-01 6 views
1

나는 TSQL 변수의 개념 및 SQL Server 여기변수 초보자

을 잡고 몇 가지 문제가 오전에 설명 저장 프로 시저의 예입니다 . 사용자가 InoviceID 만 입력하는 경우 누군가 SELECT 문이 어떻게 작동하는지 그리고 두 번째 SELECT 문이 어떻게 작동하는지 설명 할 수 있습니까?

  1. 사용자가 입력 한 InvoiceID에 따라 첫 번째로 말하지만 InvoiceID를 사용하여 나중에 사용할 수 있도록 채우는 데 사용됩니까?
  2. 그렇다면 InvoiceGuid가 동일한 값을 가진 SP에서 반복적으로 사용될 수 있습니까?

더 이상 설명해야하는지 알려주세요.

+1

1) 예 2) 예. 가정을 테스트하는 데 몇 분을 보내는 것이 더 쉽지 않습니까? 적절한 데이터 유형을 사용하는 경향이 있습니다. 무언가가'guid'라면 - 그것이'uniqueidentifier' 유형의 진짜 안내자가되게하십시오. –

+0

@IvanStarostin 당신은 유효한 가정을 테스트하고, 나의 가정을 테스트하는 것은 좋은 습관입니다. – Austin44

답변

1

은 항상 나에게 조금 이상한보고있다.

SELECT @InvoiceGuid = c.InvoiceGuid 
FROM customers c 
WHERE c.InvoiceID = @InvoiceID 

효과적으로 이것은 @InvoiceID는 파라미터로서 절차에 전달 된 값을 사용하여

@InvoiceGuid = (SELECT c.InvoiceGuid 
FROM customers c 
WHERE c.InvoiceID = @InvoiceID) 

을 의미한다.

0

select@InvoiceGuid 값을 할당하기 위해 지정된 @InvoiceID를 사용하며, 그 값은 프로 시저를 호출 할 때 @InvoiceGuid에 전달 된 값을 덮어.

@InvoiceID 또는 @InvoiceGuID을 받아들이는 단일 절차를 만들려는 경우 값을 확인하여 어느 것이 빈 문자열인지 확인하고 적절한 선택을 할 수 있습니다.

1

여기에 약간의 테스트 데이터 당신 구문 SQL이에 사용

DECLARE 
    @InvoiceID int = null, 
    @InvoiceGUID uniqueidentifier = null, 
    @CustomerGUID uniqueidentifier = null 

    SET @InvoiceID = 1000 


    IF OBJECT_ID ('tempdb..#Invoices') IS NOT NULL DROP TABLE #Invoices 

    CREATE TABLE #Invoices(
     InvoiceID varchar(28), 
     InvoiceGUID uniqueidentifier, 
     CustomerGUID uniqueidentifier) 

    declare @ct int = 0 

    WHILE @ct < 5 
    BEGIN 
     INSERT INTO #Invoices (InvoiceID, InvoiceGUID, CustomerGUID) 
     SELECT 
      1000 + @ct as InvoiceID, 
      NEWID() as InvoiceGUID, 
      NEWID() as CustomerGUID 
     SET @ct = @ct + 1 
    END 

    --Check your data to see what we filled 
    SELECT * From #Invoices 


    --Here we are setting the variable @InvoiceGUID to the GUID for the Invoice which you passed in via @InvoiceID. 
    --It will overwrite anything that is in the @InvoiceGUID, for example, if you passed something in. 
    SELECT 
     @InvoiceGUID = InvoiceGUID 
    FROM 
     #Invoices 
    WHERE 
     InvoiceID = @InvoiceID 

    --Check to make sure we got the variable. Also compare this to the table. It should be the same. 
    SELECT @InvoiceGUID as InvoiceGUIDparameter 



    --Now set the @CustomerGUID based off the @InvoiceGUID we just selected. 
    SELECT 
     @CustomerGUID = CustomerGUID 
    FROM 
     #Invoices 
    WHERE 
     InvoiceGUID = @InvoiceGUID 


    --Check the value to compare 
    SELECT @CustomerGUID as CustomerGUIDparameter 


    --The only catch here is TSQL batches. Your parameters won't be "global" so to speak if you have mutlple batch statements. 
    --https://technet.microsoft.com/en-us/library/ms175502(v=sql.105).aspx 
    --https://msdn.microsoft.com/en-us/library/ms712553(v=vs.85).aspx 
+0

감사합니다. 나는 이것을 시험해 보겠습니다! – Austin44

+0

질문이 있으시면 언제든지 저희에게 알려주십시오. – scsimon