Test
SQL Quiz
Preguntas del test (66)
1Your database contains two tables named DomesticSalesOrders and InternationalSalesOrders. Both tables contain more than 100 million rows. Each table has a Primary Key column named SalesOrderId. The data
in the two tables is distinct from one another. Business users want a report that includes aggregate information about the total number of global sales and total sales amounts. You need to ensure that your query executes in the minimum possible time. Which query should you use?- A SELECT COUNT(*) AS NumberOfSales, SUM(SalesAmount) AS TotalSalesAmount
FROM (
SELECT SalesOrderId, SalesAmount
FROM DomesticSalesOrders
UNION ALL
SELECT SalesOrderId, SalesAmount
FROM InternationalSalesOrders
) AS p - BSELECT COUNT(*) AS NumberOfSales, SUM(SalesAmount) AS TotalSalesAmount
FROM (
SELECT SalesOrderId, SalesAmount
FROM DomesticSalesOrders
UNION
SELECT SalesOrderId, SalesAmount
FROM InternationalSalesOrders
) AS p - C SELECT COUNT(*) AS NumberOfSales, SUM(SalesAmount) AS TotalSalesAmount
FROM DomesticSalesOrders
UNION
SELECT COUNT(*) AS NumberOfSales, SUM(SalesAmount) AS TotalSalesAmount
FROM InternationalSalesOrders - DSELECT COUNT(*) AS NumberOfSales, SUM(SalesAmount) AS TotalSalesAmount
FROM DomesticSalesOrders
UNION ALL
SELECT COUNT(*) AS NumberOfSales, SUM(SalesAmount) AS TotalSalesAmount
- A SELECT COUNT(*) AS NumberOfSales, SUM(SalesAmount) AS TotalSalesAmount
2You are a database developer at an independent software vendor. You create stored procedures that contain proprietary code. You need to protect the code from being viewed by your customers. Which stored procedure option should you use?
- AENCRYPTBYKEY
- BENCRYPTION
- CENCRYPTBYPASSPHRASE
- DENCRYPTBYCERT
3You use a Microsoft SQL Server 2012 database. You want to create a table to store Microsoft Word documents. You need to ensure that the documents must only be accessible via Transact-SQL queries. Which Transact-SQL statement should you use?
- ACREATE TABLE DocumentStore
(
[Id] INT NOT NULL PRIMARY KEY, [Document] VARBINARY(MAX) NULL
)
GO - B CREATE TABLE DocumentStore
(
[Id] hierarchyid,
[Document] NVARCHAR NOT NULL
) - CCREATE TABLE DocumentStore AS FileTable
- DCREATE TABLE DocumentStore
(
[Id] [uniqueidentifier] ROWGUIDCOL NOT NULL UNIQUE, [Document] VARBINARY(MAX) FILESTREAM NULL
)
GO
- ACREATE TABLE DocumentStore
4A table named Profits stores the total profit made each year within a territory. The Profits table has columns named Territory, Year, and Profit. You need to create a report that displays the profits made by each territory for each year and its preceding year. Which Transact-SQL query should you use?
- ASELECT Territory, Year, Profit,
LAG(Profit, 1, 0) OVER(PARTITION BY Year ORDER BY Territory) AS
NextProfit
FROM Profits - BSELECT Territory, Year, Profit,
LAG(Profit, 1, 0) OVER(PARTITION BY Territory ORDER BY Year) AS
NextProfit
FROM Profits - CSELECT Territory, Year, Profit,
LEAD(Profit, 1, 0) OVER(PARTITION BY Territory ORDER BY Year) AS
NextProfit
FROM Profits - DSELECT Territory, Year, Profit,
LEAD(Profit, 1, 0) OVER(PARTITION BY Year ORDER BY Territory) AS
NextProfit
FROM Profits
- ASELECT Territory, Year, Profit,
5You use Microsoft SQL Server 2012 to develop a database application. Your application sends data to an NVARCHAR(MAX) variable named @var. You need to write a Transact-SQL statement that will find out the success of a cast to a decimal (36,9). Which code segment should you use?select
- ABEGIN TRY
SELECT convert(decimal(36,9), @var) AS Value, ‘True’ AS BadCast
END TRY
BEGIN CATCH
SELECT convert(decimal(36,9), @var) AS Value, ‘False’ AS BadCast
END CATCH - BTRY(
SELECT convert(decimal(36,9), @var)
SELECT ‘True’ AS BadCast
)
CATCH(
SELECT ‘False’ AS BadCast
) - C SELECT CASE
WHEN convert(decimal(36,9), @var) IS NULL THEN ‘True’
ELSE ‘False’ END
AS BadCast - DSELECT
IIF(TRY_PARSE(@var AS decimal(36,9)) IS NULL, ‘True’, ‘False’) AS BadCast
- ABEGIN TRY
6You are writing a set of queries against a FILESTREAM-enabled database. You create a stored procedure that will update multiple tables within a transaction. You need to ensure that if the stored procedure raises a run-time error, the entire transaction is terminated and rolled back. Which Transact-SQL statement should you include at the beginning of the stored procedure?
- ASET TRANSACTION ISOLATION LEVEL SERIALIZABLE
- BSET XACT_ABORT OFF
- C SET TRANSACTION ISOLATION LEVEL SNAPSHOT
- D SET IMPLICIT_TRANSACTIONS ON
- ESET XACT_ABORT ON
- F SET IMPLICIT TRANSACTIONS OFF
7You have a Microsoft SQL Server 2012 database that contains tables named Customers and Orders. The tables are related by a column named CustomerID. You need to create a query that meets the following requirements:
Returns the CustomerName for all customers and the OrderDate for any orders that they have placed. Results must include customers who have not placed any orders.
Which Transact-SQL query should you use?- ASELECT CustomerName, OrderDate
FROM Customers
RIGHT OUTER JOIN Orders
ON Customers.CustomerID = Orders.CustomerID - BSELECT CustomerName, CrderDate
FROM Customers
JOIN Orders
ON Customers.CustomerID = Orders.CustomerID - CSELECT CustomerName, OrderDate
FROM Customers
CROSS JOIN Orders
ON Customers.CustomerID = Orders.CustomerID - DSELECT CustomerName, OrderDate
FROM Customers
LEFT OUTER JOIN Orders
ON Customers.CustomerID = Orders.CustomerID
- ASELECT CustomerName, OrderDate
8You create a stored procedure that will update multiple tables within a transaction. You need to ensure that if the stored procedure raises a run-time error, the entire transaction is terminated and rolled back. Which Transact-SQL statement should you include at the beginning of the stored procedure?
- ASET XACT_ABORT ON
- BSET ARITHABORT ON
- CTRY
- DBEGIN
- ESET ARITHABORT OFF
9You develop a Microsoft SQL Server 2012 database. You need to create a batch process that meets the following requirements:
Status information must be logged to a status table.
If the status table does not exist at the beginning of the batch, it must be created.
Which object should you use?- AScalar user-defined function
- BInline user-defined function
- CTable-valued user-defined function
- D Stored procedure
10You administer a database that includes a table named Customers that contains more than 750 rows. You create a new column named PartitionNumber of the int type in the table. You need to assign a PartitionNumber for each record in the Customers table. You also need to ensure that the PartitionNumber satisfies the following conditions:
Always starts with 1.
Starts again from 1 after it reaches 100. Which Transact-SQL statement should you use?- AREATE SEQUENCE CustomerSequence AS int
START WITH 0
INCREMENT BY 1
MINVALUE 1
MAXVALUE 100
UPDATE Customers SET PartitionNumber = NEXT VALUE FOR CustomerSequence
DROP SEQUENCE CustomerSequence - BCREATE SEQUENCE CustomerSequence AS int
START WITH 1
INCREMENT BY 1
MINVALUE 1
MAXVALUE 100
CYCLE
UPDATE Customers SET PartitionNumber = NEXT VALUE FOR CustomerSequence
DROP SEQUENCE CustomerSequence - CCREATE SEQUENCE CustomerSequence AS int
START WITH 1
INCREMENT BY 1
MINVALUE 1
MAXVALUE 100
UPDATE Customers SET PartitionNumber = NEXT VALUE FOR CustomerSequence + 1
DROP SEQUENCE CustomerSequence - DCREATE SEQUENCE CustomerSequence AS int
START WITH 1
INCREMENT BY 1
MINVALUE 0
MAXVALUE 100
CYCLE
UPTATE Customers SET PartitionNumber = NEXT VALUE FOR CustomerSequence
DROP SEQUENCE CustomerSequence
- AREATE SEQUENCE CustomerSequence AS int
11You use a Microsoft SQL Server 2012 database that contains a table named BlogEntry that has the following columns:
Id is the Primary Key.
You need to append the “This is in a draft stage” string to the Summary column of the recent 10 entries based on the values in EntryDateTime. Which Transact-SQL statement should you use?- AUPDATE TOP(10) BlogEntry
SET Summary.WRITE(N’ This is in a draft stage’, NULL, 0) - BUPDATE BlogEntry
SET Summary = CAST(N’ This is in a draft stage’ as nvarchar(max))
WHERE Id IN(SELECT TOP(10) Id FROM BlogEntry ORDER BY EntryDateTime DESC) - CUPDATE BlogEntry
SET Summary.WRITE(N’ This is in a draft stage’, NULL, 0) FROM (
SELECT TOP(10) Id FROM BlogEntry ORDER BY EntryDateTime DESC) AS s
WHERE BlogEntry.Id = s.ID - DUPDATE BlogEntry
SET Summary.WRITE(N’ This is in a draft stage’, 0, 0)
WHERE Id IN(SELECT TOP(10) Id FROM BlogEntry ORDER BY EntryDateTime DESC)
- AUPDATE TOP(10) BlogEntry
12You use Microsoft SQL Server 2012 to develop a database application. You create a stored procedure named DeleteJobCandidate. You need to ensure that if DeleteJobCandidate encounters an error, the execution of the stored procedure reports the error number. Which Transact-SQL statement should you use?
- A DECLARE @ErrorVar INT; DECLARE @RowCountVar INT;
EXEC DeleteJobCandidate
SELECT @ErrorVar = @@ERROR, @RowCountVar = @@ROWCOUNT; IF (@ErrorVar <> 0)
PRINT N’Error = ‘ + CAST(@@ErrorVar AS NVARCHAR(8)) +
N’, Rows Deleted = ‘ + CAST(@@RowCountVar AS NVARCHAR(8));
GO - BDECLARE @ErrorVar INT; DECLARE @RowCountVar INT;
EXEC DeleteJobCandidate
SELECT @ErrorVar = ERROR_STATE(), @RowCountVar = @@ROWCOUNT; IF (@ErrorVar <> 0)
PRINT N’Error = ‘ + CAST(ERRORSTATE() AS NVARCHAR(8)) +
N’, Rows Deleted = ‘ + CAST(@@RowCountVar AS NVARCHAR(8));
GO - C EXEC DeleteJobCandidate
IF (ERROR_STATE() != 0)
PRINT N’Error = ‘ + CAST(@@ERROR AS NVARCHAR(8)) +
N’, Rows Deleted = ‘ + CAST(@@ROWCOUNT AS NVARCHAR(8));
GO - DEXEC DeleteJobCandidate
PRINT N’Error = ‘ + CAST(@@ERROR AS NVARCHAR(8)) +
N’, Rows Deleted = ‘ + CAST(@@ROWCOUNT AS NVARCHAR(8));
GO
- A DECLARE @ErrorVar INT; DECLARE @RowCountVar INT;
13You administer a Microsoft SQL Server 2012 database. The database contains a table named Employee. Part of the Employee table is shown in the exhibit. (Click the Exhibit button.)
EmTmp ”
Column Name Condensed Type
EmployeeID int EmployeeNum char{lO) LastNamen nvarchar(21 )
FirstNamen nvarchar(21}
MiddlName nvarchar(20) DateHired Date DepartmentID int
JobTrtJe varchar(200) ReportsToID int
Column Name
Descriptjon
EmployeeID(pk)
uniquely identifies the employee record in the table
Used throughout the database by all the other tables that reference the Employee table
EmployeeNum
an alphanumeric value calculated according to company Requirements
Has to be unique within the Employee table
Exists only within the Employee table
DepartmentID
References another table named Department that contains data each department in the company
ReportsToID
Contains the EmployeeID of the manager to whom an employee reports
ReportsToID
Contains the EmployeeID of the manager to whom an employee reports
Confidential information about lne employees is stored in a separate table named EmployeeData. One
record exists within EmployeeData for each record in the Employee table. You need to assign the appropriate constraints and table properties to ensure data integrity and visibility. On which column in the Employee table should you a create a unique constraint?- ADateHired
- BDepartmentID
- CEmployeelD
- DEmployeeNum
- EFirstName
- FJobTitle
- GReportsToID
14You administer a Microsoft SQL Server 2012 database. The database contains a table named Employee. Part of the Employee table is shown in the exhibit. (Click the Exhibit button.)
Confidential information about the employees is stored in a separate table named EmployeeData. One record exists within EmployeeData for each record in the Employee table. You need to assign the appropriate constraints and table properties to ensure data integrity and visibility. On which column in the Employee table should you use an identity specification to include a seed of 1,000 and an increment of 1?- ADateHired
- BDepartmentID
- CEmployeeID
- DEmployeeNum
- EFirstName
- FJobTitle
15You administer a Microsoft SQL Server 2012 database that includes a table named Products. The Products table has columns named Productld, ProductName, and CreatedDateTime. The table contains a unique constraint on the combination of ProductName and CreatedDateTime. You need to modify the Products table to meet the following requirements:
Remove all duplicates of the Products table based on the ProductName column. Retain only the newest Products row.
Which Transact-SQL query should you use?- AWITH CTEDupRecords
AS
(
SELECT MAX(CreatedDateTime) AS CreatedDateTime, ProductName
FROM Products
GROUP BY ProductName
HAVING COUNT(*) > 1
)
DELETE p
FROM Products p
JOIN CTEDupRecords cte ON
p.ProductName = cte.ProductName
AND p.CreatedDateTime > cte.CreatedDateTime - BWITH CTEDupRecords
AS
(
SELECT MAX(CreatedDateTime) AS CreatedDateTime, ProductName
FROM Products
GROUP BY ProductName
HAVING COUNT(*) > 1
)
DELETE p
FROM Products p
JOIN CTEDupRecords cte ON
cte.ProductName = p.ProductName
AND cte.CreatedDateTime > p.CreatedDateTime - CWITH CTEDupRecords
AS
(
SELECT MIN(CreatedDateTime) AS CreatedDateTime, ProductName
FROM Products
GROUP BY ProductName
)
DELETE p
FROM Products p
JOIN CTEDupRecords cte ON
p.ProductName = cte.ProductName - DWITH CTEDupRecords
AS
(
SELECT MAX(CreatedDateTime) AS CreatedDateTime, ProductName
FROM Products
GROUP BY ProductName
HAVING COUNT(*) > 1
)
DELETE p
FROM Products p
JOIN CTEDupRecords cte ON
p.ProductName = cte.ProductName
- AWITH CTEDupRecords
16You develop three Microsoft SQL Server 2012 databases named Database1, Database2, and Database3. You have permissions on both Database1 and Database2. You plan to write and deploy a stored procedure named dbo.usp_InsertEvent in Database3. dbo.usp_InsertEvent must execute other stored procedures in the other databases. You need to ensure that callers that do not have permissions on Database1 or Database2 can execute the stored procedure. Which Transact-SQL statement should you use?
- AUSE Database2
- BEXECUTE AS OWNER
- CUSE Database1
- DEXECUTE AS CALLER
17You use Microsoft SQL Server 2012 database to develop a shopping cart application. You need to invoke a table-valued function for each row returned by a query. Which Transact-SQL operator should you use?
- ACROSS JOIN
- BUNPIVOT
- CPIVOT
- DCROSS APPLY
18You support a database structure shown in the exhibit. (Click the Exhibit button.)
You need to write a query that displays the following details: Total sales made by sales people, year, city, and country Sub totals only at the city level and country level
A grand total of the sales amount- ASELECT SalesPerson.Name, Country, City,
DatePart(yyyy, SaleDate) AS Year, Sum(Amount) AS Total
FROM Sale INNER JOIN SalesPerson
ON Sale.SalesPersonID = SalesPerson.SalesPersonID
GROUP BY GROUPING SETS((SalesPerson.Name, Country, City, DatePart(yyyy,
SaleDate)), (Country, City), (Country), ()) - BSELECT SalesPerson.Name, Country, City,
DatePart(yyyy, SaleDate) AS Year, Sum(Amount) AS Total
FROM Sale INNER JOIN SalesPerson
ON Sale.SalesPersonID = SalesPerson.SalesPersonID
GROUP BY CUBE(SalesPerson.Name, Country, City, DatePart(yyyy, SaleDate)) - CSELECT SalesPerson.Name, Country, City,
DatePart(yyyy, SaleDate) AS Year, Sum(Amount) AS Total
FROM Sale INNER JOIN SalesPerson
ON Sale.SalesPersonID = SalesPerson.SalesPersonID
GROUP BY CUBE(SalesPerson.Name, DatePart(yyyy, SaleDate), City, Country) - DSELECT SalesPerson.Name, Country, City,
DatePart(yyyy, SaleDate) AS Year, Sum(Amount) AS Total
FROM Sale INNER JOIN SalesPerson
ON Sale.SalesPersonID = SalesPerson.SalesPersonID
GROUP BY ROLLUP(SalesPerson.Name, DatePart(yyyy, SaleDate), City, Country)
- ASELECT SalesPerson.Name, Country, City,
19You are developing a database that will contain price information. You need to store the prices that include a fixed precision and a scale of six digits. Which data type should you use?
- AFloat
- BMoney
- CSmallmoney
- DNumeric
20You administer a Microsoft SQL Server database that supports a banking transaction management application. You need to retrieve a list of account holders who live in cities that do not have a branch location. Which Transact-SQL query or queries should you use? (Each correct answer presents a complete solution. Choose all that apply.)
- ASELECT AccountHolderID FROM AccountHolder
WHERE CityID NOT IN (SELECT CityID FROM BranchMaster) - BSELECT AccountHolderID FROM AccountHolder
WHERE CityID <> ALL (SELECT CityID FROM BranchMaster) - CSELECT AccountHolderlD FROM AccountHolder
WHERE CityID <> SOME (SELECT CityID FROM BranchMaster) - DSELECT AccountHolderID FROM AccountHolder
WHERE CityID <> ANY (SELECT CityID FROM BranchMaster)
- ASELECT AccountHolderID FROM AccountHolder
21You have a database that contains the tables as shown in the exhibit. (Click the Exhibit button.)
You have the following query:
You need to recreate the query to meet the following requirements: Reference columns by using one-part names only.
Sort aggregates by SalesTerritoryID, and then by ProductID.
Order the results in descending order from SalesTerritoryID to ProductID. The solution must use the existing SELECT clause and FROM clause.
Which code segment should you use?
To answer, type the correct code in the answer area.- ASELECT SalesTerritoryID, ProductID, AVG(UnitPrice), MAX(OrderQty), MAX(DiscountAmount)
FROM Sales.Details
GROUP BY SalesTerritoryID , ProductID
ORDER BY SalesTerritoryID DESC, ProductID DESC - BManual Entry
- ASELECT SalesTerritoryID, ProductID, AVG(UnitPrice), MAX(OrderQty), MAX(DiscountAmount)
22You have a database that contains the tables shown in the exhibit. (Click the Exhibit button).
You need to create a query for a report. The query must meet the following requirements:
NOT use object delimiters.
Return the most recent orders first.
Use the first initial of the table as an alias.
Return the most recent order date for each customer. Retrieve the last name of the person who placed the order.
Return the order date in a column named MostRecentOrderDate that appears as the last column in the report.
The solution must support the ANSI SQL-99 standard. Which code segment should you use?
To answer, type the correct code in the answer area.- ASELECT C.LastName, MAX(O.OrderDate) AS MostRecentOrderDate
FROM Customers AS C INNER JOIN Orders AS O
ON C.CustomerID = O.CustomerID
GROUP BY C.LastName
ORDER BY O.OrderDate DESC - BManual Entry
- ASELECT C.LastName, MAX(O.OrderDate) AS MostRecentOrderDate
23You have an XML schema collection named Sales.InvoiceSchema. You need to declare a variable of the XML type named XML1. The solution must ensure that XML1 is validated by using Sales.InvoiceSchema. Which code segment should you use?
To answer, type the correct code in the answer area.- ADECLARE @XML1 XML(Sales.InvoiceSchema)
- BManual Entry
24You have a database that contains the tables shown in the exhibit. (Click the Exhibit button.)
You have an application named App1. You have a parameter named @Count that uses the int data type. App1 is configured to pass @Count to a stored procedure. You need to create a stored procedure named usp_Customers for Appl. Usp_Customers must meet the following requirements:
NOT use object delimiters.
Minimize sorting and counting.
Return only the last name of each customer in alphabetical order.
Return only the number of rows specified by the @Count parameter.
The solution must NOT use BEGIN and END statements.
Which code segment should you use?- ACREATE PROCEDURE usp_Customers @Count int
AS
SELECT TOP(@Count) Customers.LastName
FROM Customers
ORDER BY Customers.LastName - BManual Entry
- ACREATE PROCEDURE usp_Customers @Count int
25You develop a Microsoft SQL Server 2012 database. You create a view from the Orders and OrderDetails tables by using the following definition.
You need to ensure that users are able to modify data by using the view. What should you do?- A Create an AFTER trigger on the view.
- BModify the view to use the WITH VIEW_METADATA clause
- C Create an INSTEAD OF trigger on the view.
- DModify the view to an indexed view.
26You have a view that was created by using the following code:
You need to create an inline table-valued function named Sales.fn_OrdersByTerritory, which must meet the following requirements:
Accept the @T integer parameter.
Use one-part names to reference columns.
Filter the query results by SalesTerritoryID.
Return the columns in the same order as the order used in OrdersByTerritoryView.
Which code segment should you use?- ACREATE FUNCTION Sales.fn_OrdersByTerritory (@T int) RETURNS TABLE
AS RETURN (
SELECT OrderID,OrderDate,SalesTerrirotyID,TotalDue
FROM Sales.OrdersByTerritory
WHERE SalesTerritoryID = @T
) - BManual Entry
- ACREATE FUNCTION Sales.fn_OrdersByTerritory (@T int) RETURNS TABLE
27You have a database that contains the tables shown in the exhibit. (Click the Exhibit button.)
You deploy a new server that has SQL Server 2012 installed. You need to create a table named Sales. OrderDetails on the new server. Sales.OrderDetails must meet the following requirements:
Write the results to a disk.
Contain a new column named LineItemTotal that stores the product of ListPrice and Quantity for each row.
The code must NOT use any object delimiters.
The solution must ensure that LineItemTotal is stored as the last column in the table.
Which code segment should you use?- ACREATE TABLE Sales.OrderDetails (
ListPrice money not null,
Quantity int not null,
LineItemTotal as (ListPrice * Quantity) PERSISTED) - BManual Entry
- ACREATE TABLE Sales.OrderDetails (
28You have a database that contains the tables shown in the exhibit. (Click the Exhibit button.)
You need to create a view named uv_CustomerFullName to meet the following requirements:
The code must NOT include object delimiters.
The view must be created in the Sales schema.
Columns must only be referenced by using one-part names.
The view must return the first name and the last name of all customers.
The view must prevent the underlying structure of the customer table from being changed.
The view must be able to resolve all referenced objects, regardless of the user’s default schema.
Which code segment should you use?- ACREATE VIEW Sales.uv_CustomerFullName
WITH SCHEMABINDING
AS
SELECT FirstName, LastName
FROM Sales.Customers - BManual Entry
- ACREATE VIEW Sales.uv_CustomerFullName
29You have a database that contains the tables shown in the exhibit. (Click the Exhibit button.)
You need to create a query that calculates the total sales of each OrderId from the Sales.Details table. The solution must meet the following requirements:
Use one-part names to reference columns.
Sort the order of the results from OrderId.
NOT depend on the default schema of a user.
Use an alias of TotalSales for the calculated ExtendedAmount.
Display only the OrderId column and the calculated TotalSales column.
Which code segment should you use?- ASELECT OrderID, SUM(ExtendedAmount) AS TotalSales
FROM Sales.Details
GROUP BY OrderID
ORDER BY OrderID - BManual Entry
- ASELECT OrderID, SUM(ExtendedAmount) AS TotalSales
30You administer a Microsoft SQL Server 2012 database that contains a table named OrderDetail. You discover that the NCI_OrderDetail_CustomerID non-clustered index is fragmented. You need to reduce fragmentation. You need to achieve this goal without taking the index offline. Which Transact-SQL batch should you use?
- ACREATE INDEX NCI_OrderDetail_CustomerID ON OrderDetail.CustomerID WITH DROP EXISTING
- BALTER INDEX NCI_OrderDetail_CustomerID ON OrderDetail.CustomerID REORGANIZE
- CALTER INDEX ALL ON OrderDetail REBUILD
- DALTER INDEX NCI_OrderDetail_CustomerID ON OrderDetail.CustomerID REBUILD
31You develop a Microsoft SQL Server 2012 database. The database is used by two web applications that access a table named Products. You want to create an object that will prevent the applications from accessing the table directly while still providing access to the required data. You need to ensure that the following requirements are met:
Future modifications to the table definition will not affect the applications’ ability to access data.
The new object can accommodate data retrieval and data modification.
You need to achieve this goal by using the minimum amount of changes to the existing applications.
What should you create for each application?- Aviews
- Btable partitions
- Ctable-valued functions
- Dstored procedures
32ou develop a Microsoft SQL Server 2012 database. You need to create a batch process that meets the following requirements:
Returns a result set based on supplied parameters.
Enables the returned result set to perform a join with a table.
Which object should you use?- A Inline user-defined function
- BStored procedure
- CTable-valued user-defined function
- DScalar user-defined function
33You develop a Microsoft SQL Server 2012 database.
You need to create and call a stored procedure that meets the following requirements: Accepts a single input parameter for CustomerID.
Returns a single integer to the calling application.
Which Transact-SQL statement or statements should you use? (Each correct answer presents part of the solution. Choose all that apply.)- ACREATE PROCEDURE dbo.GetCustomerRating @Customer INT, @CustomerRatIng INT OUTPUT AS
SET NOCOUNT ON SELECT @CustomerRating = CustomerOrders/CustomerValue
FROM Customers WHERE CustomerID = @CustomerID RETURN
GO - BEXECUTE dbo.GetCustomerRatIng 1745
- CDECLARE @customerRatingBycustomer INT DECLARE @Result INT
EXECUTE @Result = dbo.GetCustomerRating
1745
, @CustomerRatingSyCustomer - DCREATE PROCEDURE dbo.GetCustomerRating @CustomerID INT, @CustomerRating INT OUTPUT AS
SET NOCOUNT ON
SELECT @Result = CustomerOrders/CustomerValue FROM Customers WHERE CustomerID = @CustomeriD RETURN @Result
GO - EDECLARE @CustomerRatIngByCustcmer INT
EXECUTE dbo.GetCustomerRating @CustomerID = 1745,
@CustomerRating = @CustomerRatingByCustomer OUTPUT - F CREATE PROCEDURE dbo.GetCustomerRating
@CustomerID INT AS
DECLARE @Result INT SET NOCOUNT ON
SELECT @Result = CustomerOrders/CustomerVaLue
FROM Customers
WHERE Customer= = @CustomerID RETURNS @Result
- ACREATE PROCEDURE dbo.GetCustomerRating @Customer INT, @CustomerRatIng INT OUTPUT AS
34You develop a Microsoft SQL Server 2012 database that contains a table named Customers. The
Customers table has the following definition:
You need to create an audit record only when either the MobileNumber or HomeNumber column is updated. Which Transact-SQL query should you use?- ACREATE TRIGGER TrgPhoneNumberChange
ON Customers FOR UPDATE
AS
IF COLUMNS_UPDATED (HomeNumber, MobileNumber)
– – Create Audit Records - BCREATE TRIGGER TrgPhoneNumberChange
ON Customers FOR UPDATE
AS
IF EXISTS( SELECT HomeNumber FROM inserted) OR
EXISTS (SELECT MobileNumber FROM inserted)
– – Create Audit Records - CCREATE TRIGGER TrgPhoneNumberChange
ON Customers FOR UPDATE
AS
IF COLUMNS_CHANGED (HomeNumber, MobileNumber)
– – Create Audit Records - DCREATE TRIGGER TrgPhoneNumberChange
ON Customers FOR UPDATE
AS
IF UPDATE (HomeNumber) OR UPDATE (MobileNumber)
– – Create Audit Records
- ACREATE TRIGGER TrgPhoneNumberChange
35You develop a Microsoft SQL Server 2012 database that has two tables named SavingAccounts and LoanAccounts. Both tables have a column named AccountNumber of the nvarchar data type. You use a third table named Transactions that has columns named TransactionId AccountNumber, Amount, and TransactionDate. You need to ensure that when multiple records are inserted in the Transactions table, only the records that have a valid AccountNumber in the SavingAccounts or LoanAccounts are inserted. Which Transact-SQL statement should you use?
- AREATE TRIGGER TrgValidateAccountNumber
ON Transactions
INSTEAD OF INSERT
AS
BEGIN
INSERT INTO Transactions
SELECT TransactionID,AccountNumber,Amount,TransactionDate FROM inserted
WHERE AccountNumber IN
(SELECT AccountNumber FROM LoanAccounts
UNION SELECT AccountNumber FROM SavingAccounts))
END - BCREATE TRIGGER TrgValidateAccountNumber
ON Transactions
FOR INSERT
AS
BEGIN
INSERT INTO Transactions
SELECT TransactionID,AccountNumber,Amount,TransactionDate FROM inserted
WHERE AccountNumber IN
(SELECT AccountNumber FROM LoanAccounts
UNION SELECT AccountNumber FROM SavingAccounts))
END - CCREATE TRIGGER TrgValidateAccountNumber
ON Transactions
INSTEAD OF INSERT
AS
BEGIN
IF EXISTS (
SELECT AccountNumber FROM inserted EXCEPT (SELECT AccountNumber FROM LoanAccounts
UNION SELECT AccountNumber FROM SavingAccounts)) BEGIN
ROLLBACK TRAN END
END - DCREATE TRIGGER TrgValidateAccountNumber
ON Transactions
FOR INSERT
AS
BEGIN
IF EXISTS (
SELECT AccountNumber FROM inserted EXCEPT
(SELECT AccountNumber FROM LoanAccounts
UNION SELECT AccountNumber FROM SavingAccounts))
BEGIN
ROLLBACK TRAN
END
END
- AREATE TRIGGER TrgValidateAccountNumber
36You develop a Microsoft SQL Server 2012 database. You create a view that performs the following tasks: Joins 8 tables that contain up to 500,000 records each.
Performs aggregations on 5 fields.
The view is frequently used in several reports. You need to improve the performance of the reports. What should you do?- A Convert the view into a table-valued function.
- BConvert the view into a Common Table Expression (CTE).
- C Convert the view into an indexed view.
- DConvert the view into a stored procedure and retrieve the result from the stored procedure into a temporary table.
37You are a database developer of a Microsoft SQL Server 2012 database. The database contains a table named Customers that has the following definition:
You need to ensure that the CustomerId column in the Orders table contains only values that exist in the
CustomerId column of the Customer table. Which Transact-SQL statement should you use?- AALTER TABLE Orders
ADD CONSTRAINT FX_Orders_CustomerID FOREIGN KEY (CustomerId) REFERENCES
Customer (CustomerId) - BALTER TABLE Customer
ADD CONSTRAINT FK_Customer_CustomerID FOREIGN KEY {CustomerID) REFERENCES
Orders (CustomerId) - CALTER TABLE Orders
ADD CONSTRAINT CK_Crders_CustomerID
CHECK (CustomerId IN (SELECT CustomerId FROM Customer)) - DALTER TABLE Customer
ADD OrderId INT NOT NULL;
ALTER TABLE Customer
ADD CONSTRAINT FK_Customer_OrderID FOREIGN KEY (CrderlD) REFERENCES Orders
(CrderlD); - EALTER TABLE Orders
ADD CONSTRAINT PK Orders CustomerId PRIMARY KEY (CustomerID)
- AALTER TABLE Orders
38You have three tables that contain data for dentists, psychiatrists, and physicians. You create a view that is used to look up their email addresses and phone numbers. The view has the following definition:
You need to ensure that users can update only the phone numbers and email addresses by using this view. What should you do?- AAlter the view. Use the EXPAND VIEWS query hint along with each SELECT statement.
- BCreate an INSTEAD OF UPDATE trigger on the view.
- CDrop the view. Re-create the view by using the SCHEMABINDING clause, and then create an index on the view.
- DCreate an AFTER UPDATE trigger on the view.
39You administer a Microsoft SQL Server 2012 database named ContosoDb. The database contains a table named Suppliers and a column named IsActive in the Purchases schema. You create a new user named ContosoUser in ContosoDb. ContosoUser has no permissions to the Suppliers table. You need to ensure that ContosoUser can delete rows that are not active from Suppliers. You also need to grant ContosoUser only the minimum required permissions. Which Transact-SQL statement should you use?
- AGRANT DELETE ON Purchases.Suppliers TO ContosoUser
- BCREATE PROCEDURE Purchases.PurgeInactiveSuppliers
WITH EXECUTE AS USER = ‘dbo’
AS
DELETE FROM Purchases.Suppliers WHERE IsActive = 0
GO
GRANT EXECUTE ON Purchases.PurgelnactiveSuppliers TO ContosoUser - CGRANT SELECT ON Purchases.Suppliers TO ContosoUser
- DCREATE PROCEDURE Purchases.PurgeInactiveSuppliers
AS
DELETE FROM Purchases.Suppliers WHERE IsActive = 0
GO
GRANT EXECUTE ON Purchases.PurgeInactiveSuppliers TO ContosoUser
40You use a contained database named ContosoDb within a domain. You need to create a user who can log on to the ContosoDb database. You also need to ensure that you can port the database to different database servers within the domain without additional user account configurations. Which type of user should you create?
- AUser mapped to a certificate
- BSQL user without login
- CDomain user
- DSQL user with login
41You administer a Microsoft SQL Server 2012 database that has multiple tables in the Sales schema. Some users must be prevented from deleting records in any of the tables in the Sales schema. You need to manage users who are prevented from deleting records in the Sales schema. You need to achieve this goal by using the minimum amount of administrative effort. What should you do?
- ACreate a custom database role that includes the users. Deny Delete permissions on the Sales schema for the custom database role.
- BInclude the Sales schema as an owned schema for the db_denydatawriter role. Add the users to the db_denydatawriter role.
- CDeny Delete permissions on each table in the Sales schema for each user.
- DCreate a custom database role that includes the users. Deny Delete permissions on each table in the
Sales schema for the custom database role.
42You administer a Microsoft SQL Server 2012 database. The database contains a Product table created by using the following definition:
You need to ensure that the minimum amount of disk space is used to store the data in the Product table. What should you do?- AConvert all indexes to Column Store indexes.
- BImplement Unicode Compression.
- C Implement row-level compression.
- D Implement page-level compression
43You generate a daily report according to the following query:
You need to improve the performance of the query. What should you do?- A Drop the UDF and rewrite the report query as follows:
WITH cte(CustomerID, LastOrderDate) AS (
SELECT CustomerID, MAX(OrderDate) AS [LastOrderDate]
FROM Sales.SalesOrder
GROUP BY CustomerID
)
SELECT c.CustomerName
FROM cte
INNER JOIN Sales.Customer c
ON cte.CustomerID = c.CustomerID
WHERE cte.LastOrderDate < DATEADD(DAY, -90, GETDATE()) - BDrop the UDF and rewrite the report query as follows:
SELECT c.CustomerName FROM Sales.Customer c WHERE NOT EXISTS (
SELECT s.OrderDate
FROM Sales.SalesOrder
WHERE s.OrderDate > DATEADD(DAY, -90, GETDATE())
AND s.CustomerID = c.CustomerID) - CDrop the UDF and rewrite the report query as follows:
SELECT DISTINCT c.CustomerName
FROM Sales.Customer c
INNER JOIN Sales.SalesOrder s
ON c.CustomerID = s.CustomerID
WHERE s.OrderDate < DATEADD(DAY, -90, GETDATE()) - DRewrite the report query as follows:
SELECT c.CustomerName
FROM Sales.Customer c
WHERE NOT EXISTS (SELECT OrderDate FROM Sales.ufnGetRecentOrders(c.
CustomerID, 90))
- A Drop the UDF and rewrite the report query as follows:
44You use Microsoft SQL Server 2012 to develop a database application. You need to implement a computed column that references a lookup table by using an INNER JOIN against another table.
What should you do?- AReference a user-defined function within the computed column.
- BCreate a BEFORE trigger that maintains the state of the computed column.
- CAdd a default constraint to the computed column that implements hard-coded values.
- DAdd a default constraint to the computed column that implements hard-coded CASE statements.
45You use Microsoft SQL Server 2012 to develop a database application. You need to create an object that meets the following requirements:
Takes an input variable
Returns a table of values
Cannot be referenced within a view
Which object should you use?- A Scalar-valued function
- B Inline function
- CUser-defined data type
- DStored procedure
46You are a database developer for an application hosted on a Microsoft SQL Server 2012 server. The database contains two tables that have the following definitions:
Global customers place orders from several countries.
You need to view the country from which each customer has placed the most orders.
Which Transact-SQL query do you use?- ASELECT c.CustomerID, c.CustomerName, o.ShippingCountry
FROM Customer c
INNER JOIN
(SELECT CustomerID, ShippingCountry,
RANK() OVER (PARTITION BY CustomerID
ORDER BY COUNT(OrderAmount) DESC) AS Rnk
FROM Orders
GROUP BY CustomerID, ShippingCountry) AS o
ON c.CustomerID = o.CustomerID
WHERE o.Rnk = 1 - BSELECT c.CustomerID, c.CustomerName, o.ShippingCountry
FROM
(SELECT c.CustomerID, c.CustomerName, o.ShippingCountry,
RANK() OVER (PARTITION BY CustomerID
ORDER BY COUNT(o.OrderAmount) ASC) AS Rnk
FROM Customer c
INNER JOIN Orders o
ON c.CustomerID = o.CustomerID
GROUP BY c.CustomerID, c.CustomerName, o.ShippingCountry) cs
WHERE Rnk = 1 - CSELECT c.CustomerID, c.CustomerName, o.ShippingCountry
FROM Customer c
INNER JOIN
(SELECT CustomerID, ShippingCountry,
RANK() OVER (PARTITION BY CustomerID
ORDER BY OrderAmount DESC) AS Rnk
FROM Orders
GROUP BY CustomerID, ShippingCountry) AS o
ON c.CustomerID = o.CustomerID
WHERE o.Rnk = 1 - D SELECT c.CustomerID, c.CustomerName, o.ShippingCountry
FROM Customer c
INNER JOIN
(SELECT CustomerID, ShippingCountry,
COUNT(OrderAmount) DESC) AS OrderAmount
FROM Orders
GROUP BY CustomerID, ShippingCountry) AS o
ON c.CustomerID = o.CustomerID
ORDER BY OrderAmount DESC
- ASELECT c.CustomerID, c.CustomerName, o.ShippingCountry
47You create a table that has the StudentCode, SubjectCode, and Marks columns to record mid-year marks for students. The table has marks obtained by 50 students for various subjects. You need to ensure that the top half of the students arranged by their average marks must be given a rank of 1 and the remaining students must be given a rank of 2. Which Transact-SQL query should you use?
- AELECT StudentCode as Code,
RANK() OVER (ORDER BY AVG (Marks) DESC) AS Value
FROM StudentMarks
GROUP BY StudentCode - BSELECT Id, Name, Marks,
DENSE_RANK() OVER (ORDER BY Marks DESC) AS Rank
FROM StudentMarks - CSELECT StudentCode as Code,
DENSE_RANK() OVER (ORDER BY AVG (Marks) DESC) AS Value
FROM StudentMarks
GROUP BY StudentCode - DSELECT StudentCode as Code,
NTILE (2) OVER (ORDER BY AVG (Marks) DESC) AS Value
FROM StudentMarks
GROUP BY StudentCode - ESELECT StudentCode AS Code,Marks AS Value FROM ( SELECT StudentCode, Marks AS Marks,
RANK() OVER (PARTITION BY SubjectCode ORDER BY Marks ASC) AS Rank
FROM StudentMarks) tmp
WHERE Rank = 1 - F SELECT StudentCode AS Code,Marks AS Value FROM ( SELECT StudentCode, Marks AS Marks,
RANK() OVER (PARTITION BY SubjectCode ORDER BY Marks DESC) AS Rank
FROM StudentMarks) tmp
WHERE Rank = 1 - GSELECT StudentCode AS Code,Marks AS Value FROM ( SELECT StudentCode, Marks AS Marks,
RANK () OVER (PARTITION BY StudentCode ORDER BY Marks ASC) AS Rank
FROM StudentMarks) tmp
WHERE Rank = 1 - HSELECT StudentCode AS Code,Marks AS Value FROM ( SELECT StudentCode, Marks AS Marks,
RANXO OVER (PARTITION BY StudentCode ORDER BY Marks DESC) AS Rank
FROM StudentMarks) tmp
WHERE Rank = 1
- AELECT StudentCode as Code,
48You create a table that has the StudentCode, SubjectCode, and Marks columns to record mid-year marks for students. The table has marks obtained by 50 students for various subjects. You need to ensure that the following requirements are met:
Students must be ranked based on their average marks.
If one or more students have the same average, the same rank must be given to these students. Consecutive ranks must be skipped when the same rank is assigned.
Which Transact-SQL query should you use?- ASELECT StudentCode as Code,
RANK() OVER(ORDER BY AVG (Marks) DESC) AS Value
FROM StudentMarks
GROUP BY StudentCode - BSELECT Id, Name, Marks,
DENSE_RANK() OVER(ORDER BY Marks DESC) AS Rank
FROM StudentMarks - CSELECT StudentCode as Code,
DENSE_RANK() OVER(ORDER BY AVG (Marks) DESC) AS Value
FROM StudentMarks
GROUP BY StudentCode - DSELECT StudentCode as Code,
NTILE(2) OVER(ORDER BY AVG (Marks) DESC) AS Value
FROM StudentMarks
GROUP BY StudentCode - ESELECT StudentCode AS Code,Marks AS Value FROM ( SELECT StudentCode, Marks AS Marks,
RANK() OVER(PARTITION BY SubjectCode ORDER BY Marks ASC) AS Rank
FROM StudentMarks) tmp
WHERE Rank = 1 - FSELECT StudentCode AS Code,Marks AS Value FROM ( SELECT StudentCode, Marks AS Marks,
RANK() OVER(PARTITION BY SubjectCode ORDER BY Marks DESC) AS Rank
FROM StudentMarks) tmp
WHERE Rank = 1 - G SELECT StudentCode AS Code,Marks AS Value FROM ( SELECT StudentCode, Marks AS Marks,
RANK() OVER(PARTITION BY StudentCode ORDER BY Marks ASC) AS Rank
FROM StudentMarks) tmp
WHERE Rank = 1 - HSELECT StudentCode AS Code,Marks AS Value FROM ( SELECT StudentCode, Marks AS Marks,
RANXO OVER(PARTITION BY StudentCode ORDER BY Marks DESC) AS Rank
FROM StudentMarks) tmp
WHERE Rank = 1
- ASELECT StudentCode as Code,
49You create a table that has the StudentCode, SubjectCode, and Marks columns to record mid-year marks for students. The table has marks obtained by 50 students for various subjects. You need to retrieve the students who scored the highest marks for each subject along with the marks. Which Transact-SQL query should you use?
- A SELECT StudentCode as Code, RANK() OVER(ORDER BY AVG(Marks) DESC) AS Value
FROM StudentMarks
GROUP BY StudentCode - BSELECT Id, Name, Marks, DENSE_RANK() OVER(ORDER BY Marks DESC) AS Rank
FROM StudentMarks - C SELECT StudentCode as Code, DENSE_RANK() OVER(ORDER BY AVG(Marks) DESC) AS Value
FROM StudentMarks
GROUP BY StudentCode - DSELECT StudentCode as Code, NTILE(2) OVER(ORDER BY AVG(Marks) DESC) AS Value
FROM StudentMarks
GROUP BY StudentCode - ESELECT StudentCode AS Code, Marks AS Value FROM ( SELECT StudentCode, Marks AS Marks,
RANK() OVER(PARTITION BY SubjectCode ORDER BY Marks ASC) AS Rank
FROM StudentMarks) tmp
WHERE Rank = 1 - FSELECT StudentCode AS Code, Marks AS Value FROM ( SELECT StudentCode, Marks AS Marks,
RANK() OVER(PARTITION BY SubjectCode ORDER BY Marks DESC) AS Rank
FROM StudentMarks) tmp
WHERE Rank = 1 - GSELECT StudentCode AS Code, Marks AS Value FROM ( SELECT StudentCode, Marks AS Marks,
RANK() OVER(PARTITION BY StudentCode ORDER BY Marks ASC) AS Rank
FROM StudentMarks) tmp
WHERE Rank = 1 - HSELECT StudentCode AS Code, Marks AS Value FROM ( SELECT StudentCode, Marks AS Marks,
RANXO OVER(PARTITION BY StudentCode ORDER BY Marks DESC) AS Rank
FROM StudentMarks) tmp
WHERE Rank = 1
- A SELECT StudentCode as Code, RANK() OVER(ORDER BY AVG(Marks) DESC) AS Value
50You develop a database for a travel application. You need to design tables and other database objects. You create a stored procedure. You need to supply the stored procedure with multiple event names and their dates as parameters. What should you do?
- A Use the CAST function
- BUse the DATE data type.
- CUse the FORMAT function
- DUse an appropriate collation
- EUse a user-defined table type.
- FUse the VARBINARY data type
- GUse the DATETIME data type
- HUse the DATETIME2 data type
51You are developing a database application by using Microsoft SQL Server 2012. An application that uses a
database begins to run slowly. You discover that a large amount of memory is consumed by single-use dynamic queries. You need to reduce procedure cache usage from these statements without creating any additional indexes. What should you do?- A Add a HASH hint to the query
- BAdd an INCLUDE clause to the index.
- CAdd a columnstore index to cover the query.
- DEnable the optimize for ad hoc workloads option.
- ECover the unique clustered index with a columnstore index.
- FInclude a SET FORCEPLAN ON statement before you run the query.
- G Include a SET STATISTICS PROFILE ON statement before you run the query.
- HInclude a SET TRANSACTION ISOLATION LEVEL REPEATABLE READ statement before you run the query.
- I Include a SET TRANSACTION ISOLATION LEVEL SNAPSHOT statement before you run the query.
- J Include a SET TRANSACTION ISOLATION LEVEL SERIALIZABLE statement before you run the
query.
52You use Microsoft SQL Server 2012 to write code for a transaction that contains several statements. There is high contention between readers and writers on several tables used by your transaction. You need to minimize the use of the tempdb space. You also need to prevent reading queries from blocking writing queries. Which isolation level should you use?
- ASERIALIZABLE
- BSNAPSHOT
- CREAD COMMITTED SNAPSHOT
- DREPEATABLE READ
53Your database contains a table named SalesOrders. The table includes a DATETIME column named OrderTime that stores the date and time each order is placed. There is a non-clustered index on the OrderTime column. The business team wants a report that displays the total number of orders placed on the current day. You need to write a query that will return the correct results in the most efficient manner. Which Transact-SQL query should you use?
- ASELECT COUNT(*) FROM SalesOrders
WHERE OrderTime = CONVERT(DATE, GETDATE()) - BSELECT COUNT(*) FROM SalesOrders
WHERE OrderTime = GETDATE() - CSELECT COUNT(*) FROM SalesOrders
WHERE CONVERT(VARCHAR, OrderTime, 112) = CONVERT(VARCHAR, GETDATE(I, 112)) - D SELECT COUNT(*) FROM SalesOrders
WHERE OrderTime >= CONVERT(DATE, GETDATE())
AND OrderTime < DATEADD(DAY, CONVERT(DATE, GETDATE()))
- ASELECT COUNT(*) FROM SalesOrders
54Your application contains a stored procedure for each country. Each stored procedure accepts an employee identification number through the @EmpID parameter. You plan to build a single process for each employee that will execute the stored procedure based on the country of residence. Which approach should you use?
- Aa recursive stored procedure
- BTrigger
- C An UPDATE statement that includes CASE
- D Cursor
- EThe foreach SQLCLR statement
55You use Microsoft SQL Server 2012 to develop a database application. You create a stored procedure named dbo.ModifyData that can modify rows. You need to ensure that when the transaction fails, dbo. ModifyData meets the following requirements:
Does not return an error
Closes all opened transactions
Which Transact-SQL statement should you use?- ABEGIN TRANSACTION
BEGIN TRY
EXEC dbo.ModifyData
COMMIT TRANSACTION
END TRY
BEGIN CATCH
IF @@ TRANCOUNT = 0
ROLLBACK TRANSACTION;
END CATCH - BBEGIN TRANSACTION BEGIN TRY
EXEC dbo.ModifyData
COMMIT TRANSACTION
END TRY
BEGIN CATCH
IF @@ERROR != 0
ROLLBACK TRANSACTION;
THROW;
END CATCH - CBEGIN TRANSACTION BEGIN TRY
EXEC dbo.ModifyData
COMMIT TRANSACTION
END TRY
BEGIN CATCH
IF @@TRANCOUNT = 0
ROLLBACK TRANSACTION;
THROW;
END CATCH - DBEGIN TRANSACTION BEGIN TRY
EXEC dbo.ModifyData
COMMIT TRANSACTION
END TRY
BEGIN CATCH
IF @@ERROR != 0
ROLLBACK TRANSACTION;
END CATCH
- ABEGIN TRANSACTION
56You are developing a database application by using Microsoft SQL Server 2012. An application that uses a database begins to run slowly. You discover that during reads, the transaction experiences blocking from concurrent updates. You need to ensure that throughout the transaction the data maintains the original
version. What should you do?- AInclude a SET TRANSACTION ISOLATION LEVEL SNAPSHOT statement before you run the query.
- BInclude a SET TRANSACTION ISOLATION LEVEL REPEATABLE READ statement before you run the query.
- C Add a HASH hint to the query.
- DEnable the optimize for ad hoc workloads option.
- Eover the unique clustered index with a columnstore index.
- FInclude a SET FORCEPLAN ON statement before you run the query.
57You are developing a database application by using Microsoft SQL Server 2012. You have a query that runs slower than expected. You need to capture execution plans that will include detailed information on missing indexes recommended by the query optimizer. What should you do?
- A Include a SET STATISTICS SHOWPLAN_XML ON statement before you run the query.
- B Include a SET STATISTICS PROFILE ON statement before you run the query.
- C Include a SET FORCEPLAN ON statement before you run the query.
- DAdd a FORCESCAN hint to the Attach query.
- EAdd an INCLUDE clause to the index.
- F Include a SET TRANSACTION ISOLATION LEVEL SNAPSHOT statement before you run the query.
58Your database contains tables named Products and ProductsPriceLog. The Products table contains columns named ProductCode and Price. The ProductsPriceLog table contains columns named ProductCode, OldPrice, and NewPrice. The ProductsPriceLog table stores the previous price in the OldPrice column and the new price in the NewPrice column. You need to increase the values in the Price column of all products in the Products table by 5 percent. You also need to log the changes to the ProductsPriceLog table. Which Transact-SQL query should you use?
- AUPDATE Products SET Price = Price * 1.05
OUTPUT inserted.ProductCode, deleted.Price, inserted.Price
INTO ProductsPriceLog(ProductCode, OldPrice, NewPrice) - BUPDATE Products SET Price = Price * 1.05
OUTPUT inserted.ProductCode, inserted.Price, deleted.Price
INTO ProductsPriceLog(ProductCode, OldPrice, NewPrice) - CUPDATE Products SET Price = Price * 1.05
OUTPUT inserted.ProductCode, deleted.Price, inserted.Price *
INTO ProductsPriceLog(ProductCode, OldPrice, NewPrice) - DUPDATE Products SET Price = Price * 1.05
INSERT INTO ProductsPriceLog (ProductCode, CldPnce, NewPrice;
SELECT ProductCode, Price, Price * 1.05 FROM Products
- AUPDATE Products SET Price = Price * 1.05
59A table named Profits stores the total profit made each year within a territory. The Profits table has columns named Territory, Year, and Profit. You need to create a report that displays the profits made by each territory for each year and its previous year. Which Transact-SQL query should you use?
- ASELECT Territory, Year, Profit,
LEAD(Profit, 1, 0) OVER (PARTITION BY Territory ORDER BY Year) AS
PrevProfit
FROM Profits - BSELECT Territory, Year, Profit,
LAG(Profit, 1, 0) OVER (PARTITION BY Year ORDER BY Territory) AS
PrevProfit
FROM Profits - CSELECT Territory, Year, Profit,
LAG(Profit, 1, 0) OVER (PARTITION BY Territory ORDER BY Year) AS
PrevProfit
FROM Profits - DSELECT Territory, Year, Profit,
LEAD(Profit, 1, 0) OVER (PARTITION BY Year ORDER BY Territory) AS
PrevProfit
FROM Profits
- ASELECT Territory, Year, Profit,
60You use Microsoft SQL Server 2012 database to develop a shopping cart application. You need to rotate
the unique values of the ProductName field of a table-valued expression into multiple columns in the output. Which Transact-SQL operator should you use?- ACROSS JOIN
- BCROSS APPLY
- CPIVOT
- DUNPIVOT
61You administer a Microsoft SQL Server database that supports a shopping application. You need to retrieve a list of customers who live in territories that do not have a sales person. Which Transact- SQL query or queries should you use? (Each correct answer presents a complete solution. Choose all that apply.)
- ASELECT CustomerID FROM Customer
WHERE TerritoryID <> SOME(SELECT TerritoryID FROM Salesperson) - BSELECT CustomerID FROM Customer
WHERE TerritoryID <> ALL(SELECT TerritoryID FROM Salesperson) - CSELECT CustomerID FROM Customer
WHERE TerritoryID <> ANY(SELECT TerritoryID FROM Salesperson) - DSELECT CustomerID FROM Customer
WHERE TerritoryID NOT IN(SELECT TerritoryID FROM Salesperson)
- ASELECT CustomerID FROM Customer
62You are a database developer of a Microsoft SQL Server 2012 database. You are designing a table that will store Customer data from different sources. The table will include a column that contains the CustomerID from the source system and a column that contains the SourceID. A sample of this data is as shown in the following table.
You need to ensure that the table has no duplicate CustomerID within a SourceID. You also need to ensure that the data in the table is in the order of SourceID and then CustomerID. Which Transact- SQL statement should you use?- ACREATE TABLE Customer
(SourceID int NOT NULL IDENTITY,
CustomerID int NOT NULL IDENTITY,
CustomerName varchar(255) NOT NULL); - BCREATE TABLE Customer
(SourceID int NOT NULL,
CustomerID int NOT NULL PRIMARY KEY CLUSTERED,
CustomerName varchar(255) NOT NULL); - CCREATE TABLE Customer
(SourceID int NOT NULL PRIMARY KEY CLUSTERED,
CustomerID int NOT NULL UNIQUE,
CustomerName varchar(255) NOT NULL); - DCREATE TABLE Customer (SourceID int NOT NULL, CustomerID int NOT NULL,
CustomerName varchar(255) NOT NULL, CONSTRAINT PK_Customer PRIMARY KEY CLUSTERED (SourceID, CustomerID));
- ACREATE TABLE Customer
63You develop a Microsoft SQL Server 2012 database that contains tables named Employee and Person. The tables have the following definitions:
You create a view named VwEmployee as shown in the following Transact-SQL statement.
Users are able to use single INSERT statements or INSERT…SELECT statements into this view. You need to ensure that users are able to use a single statement to insert records into both Employee and Person tables by using the VwEmployee view. Which Transact-SQL statement should you use?- ACREATE TRIGGER TrgVwEmployee
IN VwEmployee
FOR INSERT
AS
BEGIN
INSERT INTO Person(Id, FirstName,LastName) SELECT Id, FirstName, LastNameFROM inserted
INSERT INTO Employee(PersonId, EmployeeNumber) SELECT Id,EmployeeNumber FROM inserted
END - BCREATE TRIGGER TrgVwEmployee
IN VwEmployee
INSTEAD OF
AS
BEGIN
INSERT INTO Person(Id, FirstName,LastName) SELECT Id, FirstName, LastNameFROM inserted
INSERT INTO Employee(PersonId, EmployeeNumber) SELECT Id,EmployeeNumber FROM inserted
END - CCREATE TRIGGER TrgVwEmployee
N VwErr loyee INSTEAD OF INSERT AS
BEGIN
DECLARE @ID INT@F rstName NVARCHAR( 5) @LastName NVARCHAR( 5) @PersonID INT @EmployeeNumber NVARCR(15)
SELECT @ID 1@F rstNameF rstName @LastNameLastName
EmployeeNumberEmployeeNumber
FROM serted
INSERT INTO Person(Id F rstNameLastName) VALUES(@ID @F rstName@LastName)
INSERT INTO Employee(Person EmployeeNumber) VALUES(@PersonID @EmployeeNumber
End - DCREATE TRIGGER TrgVwEmployee
IN VwEmployee
INSTEAD OF
AS
BEGIN
INSERT INTO Person(Id, FirstName,LastName) SELECT Id, FirstName, LastNameFROM VwEmployee
INSERT INTO Employee(PersonId, EmployeeNumber) SELECT Id,EmployeeNumber FROM VwEmployee
END
- ACREATE TRIGGER TrgVwEmployee
64You develop a Microsoft SQL Server 2012 server database that supports an application. The application contains a table that has the following definition:
CREATE TABLE Inventory
(ItemID int NOT NULL PRIMARY KEY,
ItemsInStore int NOT NULL,
ItemsInWarehouse int NOT NULL)
You need to create a computed column that returns the sum total of the ItemsInStore and
ItemsInWarehouse values for each row. Which Transact-SQL statement should you use?- AALTER TABLE Inventory
ADD TotalItems AS ItemsInStore + ItemsInWarehouse - BLTER TABLE Inventory
ADD ItemsInStore – ItemsInWarehouse = TotalItems - CALTER TABLE Inventory
ADD TotalItems = ItemsInStore + ItemsInWarehouse - DALTER TABLE Inventory
ADD TotalItems AS SUM(ItemsInStore, ItemslnWarehouse);
- AALTER TABLE Inventory
65You develop a Microsoft SQL Server 2012 database that contains a heap named OrdersHistorical. You write the following Transact-SQL query:
INSERT INTO OrdersHistorical
SELECT * FROM CompletedOrders
You need to optimize transaction logging and locking for the statement. Which table hint should you use?- AHOLDLOCK
- BROWLOCK
- CXLOCK
- DUPDLOCK
- ETABLOCK
66You develop a Microsoft SQL Server 2012 server database that supports an application. The application contains a table that has the following definition:
CREATE TABLE Inventory (
ItemID int NOT NULL PRIMARY KEY,
ItemsInStore int NOT NULL,
ItemsInWarehouse int NOT NULL)
You need to create a computed column that returns the sum total of the ItemsInStore and ItemsInWarehouse values for each row. The new column is expected to be queried heavily, and you need to be able to index the column. Which Transact-SQL statement should you use?- AALTER TABLE Inventory
ADD TotalItems AS ItemslnStore + ItemsInWarehouse - BALTER TABLE Inventory
ADD TotalItems AS ItemsInStore + ItemsInWarehouse PERSISTED - CALTER TABLE Inventory
ADD TotalItems AS SUM(ItemsInStore, ItemsInWarehouse) PERSISTED - DALTER TABLE Inventory
ADD TotalItems AS SUM(ItemsInStore, ItemsInWarehouse)
- AALTER TABLE Inventory
Información
- Descripción
- A collection of random questions and dumps
- Autor
- R M
- Idioma
- English
- Visitas
- 867
- Etiquetas
- Valoración
- 5,0 de 5 · 3 valoraciones Valora este test