Welcome to Sign in | Help
in Search

calculul unei valori in functie de alta

Last post 10-06-2006, 10:06 PM by xmldeveloper. 1 replies.
Sort Posts: Previous Next
  •  10-06-2006, 10:03 PM 268

    calculul unei valori in functie de alta

    As dori sa creez un tabel in care sa se calculeze automat coloana pret_cu_tva la introducerea datelor in coloana pret_fara_tva.Cum pot face asta?
    Sorin Titu
    MCITP Database Administrator
    MCITP Enterprise Administrator
    Filed under:
  •  10-06-2006, 10:06 PM 269 in reply to 268

    Re: calculul unei valori in functie de alta

    Sunt mai multe solutii printre care folosirea unei coloane calculate.
    Un exemplu folosind o coloana calculata este urmatorul:

    USE tempdb;
    GO
    CREATE TABLE myTable(ID INT NOT NULL PRIMARY KEY,
          PRET_FARA_TVA DEC(19,2),
          PRET_CU_TVA AS PRET_FARA_TVA * 1.19)
    GO
    INSERT INTO myTable(ID,PRET_FARA_TVA) VALUES (1,100);
    GO
    SELECT * FROM myTable;
    GO
    -- Output
    -- ID PRET_FARA_TVA PRET_CU_TVA 
    --  1 100.00        119.00

    Acelasi exemplu un pic mai elegant, folosind o functie:

    USE tempdb;
    GO
    CREATE FUNCTION dbo.fnGetTVA(@PRET DEC(19,2))
    RETURNS DEC(19,2)
    AS
    BEGIN
    RETURN @PRET * 1.19
    END
    GO
    CREATE TABLE myTable2(ID INT NOT NULL PRIMARY KEY,
                PRET_FARA_TVA DEC(19,2),
                PRET_CU_TVA AS dbo.fnGetTVA(PRET_FARA_TVA))
    GO
    INSERT INTO myTable2(ID,PRET_FARA_TVA) VALUES (1,100);
    GO
    SELECT * FROM myTable2;
    GO
    -- Output
    -- ID PRET_FARA_TVA PRET_CU_TVA 
    --  1 100.00        119.00 

    Am dat exemplul folosind baza de date tempdb pentru a nu fi necesara stergerea obiectelor (tempdb fiind recreata la fiecare restart al serverului).


    Cristian Andrei Lefter, SQL Server MVP
    MCT, MCSA, MCDBA, MCAD, MCSD .NET,
    MCTS, MCITP - Database Administrator SQL Server 2005
    http://sqlserver.ro
View as RSS news feed in XML
Powered by Community Server (Commercial Edition), by Telligent Systems