Quantcast
Channel: SQLServerCentral » SQL Server 2012 » SQL Server 2012 - T-SQL » Latest topics
Viewing all 4901 articles
Browse latest View live

How to reduce the joins in sql querry

$
0
0
Hi I have select query with 10 Joins in place with different i want to improve the performance of the query how do i join tables with out joinsthanksPradeep

Passing multiple values to a parameter in a stored produre

$
0
0
Can anyone help, I have the following stored procedurecreate procedure TEST_procedure @exampleid asupdate tableaset text_field = 'Y'whereexample_id in (@exampleid)I would like to be able to pass multiple values to the @example id parameter so the procedure will update the relevant fields.I'm not sure how to do this without creating more parameters.

Select statement to return sum by year

$
0
0
I am working on a query to show a sum of costs by year in a vendor purchase table. the final output I am trying to achieve will show the Vendor Number, Vendor Name, Year, Total Sum. Below is a sample table. [code="sql"]CREATE TABLE [dbo].[tempVendorPurchases]( [VendorNum] [INT] NOT NULL, [Amount] [int] NOT NULL, [PostingDate] [Date] NOT NULL, [VendorName] [varchar](20) NOT NULL,) GOinsert into [dbo].[tempVendorPurchases]( [VendorNum],[Amount], [PostingDate], [VendorName])Values( '1234', '100', '2012-01-15', 'SoftwareCo'),( '1234', '10000', '2013-02-15', 'SoftwareCo'),( '1234', '12500', '2011-02-15', 'SoftwareCo'),( '1234', '15300', '2012-03-15', 'SoftwareCo'),( '1234', '13450', '2011-08-15', 'SoftwareCo'),( '1234', '10150', '2012-05-15', 'SoftwareCo'),( '1234', '18000', '2013-06-15', 'SoftwareCo')Select * from [dbo].[tempVendorPurchases];[/code]The end result would look like the below set. [code="plain"]Vendor Number Vendor Name Year TotalSum1234 SoftwareCo 2011 259501234 SoftwareCo 2012 255501234 SoftwareCo 2013 28000[/code]Any suggestions are welcome. Thanks.

identifying many to many relationship between columns

$
0
0
Hello All,I am struggling with something that is conceptually simple but I'm at a loss at how to implement it. I have two columns with a many to many relationship between the columns;ITEM1 ITEM2 0224180 02241810224180 02241900224181 02241800224181 02241900224190 02241800224190 02241810202294 02022950202295 02022940209250 02092510209251 0209250I need to add a single identifier that will allow these cross referenced parts to be queried. The desired outcome would be something like;ITEM1 ITEM2 ID0224180 0224181 10224180 0224190 10224181 0224180 10224181 0224190 10224190 0224180 10224190 0224181 10202294 0202295 20202295 0202294 20209250 0209251 30209251 0209250 3I hope this is clear and can attach a script or data if necessary.Thanks in Advance,Lonnie

blocking queries

$
0
0
i have this queries that are block , i have rewritten them , any suggestions to make it betterBLOCKERinsert into BREx.BusinessRuleEngine( BSSCommOrder_OrderXID,BusinessRuleEngineDefinitionID,BusinessRuleEngineDefinitionSet,Live,BusinessRuleEngineActionTypeID,BusinessRuleEngineStatusTypeID )--now check based on last order attached to customerselect c.BSSCommOrder_OrderXID,c.BusinessRuleEngineDefinitionID,c.BusinessRuleEngineDefinitionSet,bed.Live,bed.BusinessRuleEngineActionTypeID ,1 --To be determined.from breX.[vwBusinessRuleEngine_ChecksBasedOnOrder] cjoin breX.BusinessRuleEngineDefinition bed (readuncommitted) on c.BusinessRuleEngineDefinitionID = bed.BusinessRuleEngineDefinitionIDwhere c.Status_BusinessRuleEngineDefinitionCheckSet=1The querry that the above BRE querry blocks is as belowBLOCKING1. The SQL below is from the ProcessorINSERT INTO @BEMain (BusinessExceptionID ,BE_ETS_LinkGroupID ,BE_ETS_LinkRuleID ,LinkItemTypeID ,beValue ,CompareValue ,MainCaseNum)SELECT bus.BusinessExceptionID,bus.BE_ETS_LinkGroupID,bus.BE_ETS_LinkRuleID,bus.LinkItemTypeID,bus.beValue,mc.CompareValue,mc.MainCaseNumFROM ( -- Get BusinessExceptionData like parameter, processname etcSELECT bec.BusinessExceptionID,belr.BE_ETS_LinkGroupID ,belr.BE_ETS_LinkRuleID ,belr.LinkItemTypeID ,ipeX.fnBE_ETS_GetLinkItemValue(belr.LinkItemTypeID,belr.LinkItemValue,bec.BusinessExceptionID) AS beValueFROM be.BusinessException bec WITH (READUNCOMMITTED)JOIN ipeX.BE_ETS_LinkRule belr WITH (READUNCOMMITTED) ON belr.BE_ETS_LinkRuleID IS NOT NULLJOIN ipeX.vwBE_ETS_LinkSelection vbels WITH (READUNCOMMITTED) ON bec.BusinessExceptionID = vbels.BusinessExceptionID) AS busCROSS APPLY ipeX.fnBE_ETS_MatchLinkItemValueToMaincase(bus.BE_ETS_LinkRuleID, SUBSTRING(bus.beValue, 1, 60)) mc

Summarize data over contiguous date ranges

$
0
0
I could use some help to achieve the below resultsSuppose I have a table of Start/End dates and values as below:[code="sql"]IF OBJECT_ID('tempdb..#_tempData', 'U') IS NOT NULL DROP TABLE #_tempDataCREATE TABLE #_tempData ( ID INT ,StartDate DATE ,EndDate DATE ,Value1 INT ,Value2 INT);INSERT INTO #_tempDataVALUES (1,'2010-10-01','2010-10-31',0,1000) ,(1,'2010-10-01','2011-09-30',1000,0) ,(1,'2011-05-01','9999-12-31',100,0) ,(1,'2011-10-01','9999-12-31',2000,0) ,(1,'2011-12-01','2011-12-31',0,1000) ,(2,'2012-01-01','2012-01-31',0,2000) ,(2,'2012-01-01','2012-12-31',2000,0) ,(2,'2013-01-01','9999-12-31',3000,0);SELECT * FROM #_tempData;[/code]And I want to consolidate the data in the table so that any overlapping date periods are consolidated into one row and the value columns are aggregated. My desired results:[code="sql"]SELECT ID ,StartDate ,EndDate ,Value1 ,Value2FROM (VALUES (1,'2010-10-01', '2010-10-31', 1000, 1000) ,(1,'2010-11-01', '2011-04-30', 1000, 0) ,(1,'2011-05-01', '2011-09-30', 1100, 0) ,(1,'2011-10-01', '2011-11-30', 2100, 0) ,(1,'2011-12-01', '2011-12-31', 2100, 1000) ,(1,'2012-01-01', '9999-12-31', 2100, 0) ,(2,'2012-01-01', '2012-01-31', 2000, 2000) ,(2,'2012-02-01', '2012-12-31', 2000, 0) ,(2,'2013-01-01', '9999-12-31', 3000, 0) ) DesiredResults (ID, StartDate, EndDate, Value1, Value2)[/code]Can anyone write a nice query to do it?Notes1) Using SQL Server 20122) Non-overlapping date periods should not be consolidated.3) The Value columns need to be aggregated at ID levelThanks very much!

Cannot execute as the database principal

$
0
0
I have been handed a task. I don't have a lot of experiance in SQL. I know this probably isn't the best approach. But, it is what I have been asked to make work (I can't sign the code or use asymetric keys). When I execute a stored procedure I get the following error. I think it is related to double impersonation with local SQL accounts.Msg 15517 - Cannot execute as the database principal because the principal "user1" does not exist, this type of principal cannot be impersonated, or you do not have permission.We have two diffrent instaces of MSSQL. Each instance has a database. In Instance 1 we have Database A. In Instance 2 we have Database B. We have a linked server in Instance 1 that connects to Database B. In Database A we have a stored procedure that retrieves data using the linked server from Database B. This stored procedure uses Execute As User with the impersonated account User1 and works when I run it from the console. However, when it is run in a script or from the console it fails. The stored procedure is being called with the Execute As User with the account user5. How can I get the double impersonation to work? For example:We are calling the stored procedure this: use 'Database A' go execute as user = 'user5' go schema-1.StoredProcedure_GetData The stored procedure is executing a select statement with the Execute As User = 'user1' [center] Script 1 EXECUTE AS USER = 'user5' (run against DB-A) (Runs Stored Proc-1 on DB-A) (Fails Here??) | | MSSQL Instance-1 | | MSQL DB-A | | | Stored Proc-1 EXECUTE AS USER = 'user1' (Gets data from DB-B) (Using Linked Server) (Execute AS USER seems to work) || ||MSQL Linked SVR 1 || || MSSQL Instance-2 | | |MSQL DB-B[/center]

2 records at a time?

$
0
0
Hi everyone,I'm not even sure how to word this succinctly enough to search for this topic, so I apologize in advance if this is covered elsewhere! It almost feels like a gaps and islands issue, but not quite....Background Info:I am developing a form for a mortgage company. There can be any number of borrowers on a given loan, and the business has asked that this form return only 2 borrowers at a time for a loan. For example, if there are 3 borrowers for a loan, they want the first copy of the form to print the first 2 borrowers and then another copy of the form to print the 3rd. No matter how many copies are printed, they want the borrower information to be labeled as 'Borrower1' xyz and 'Borrower2' xyz. Also, there will be a LOT more fields returned on the real form, so the sample information below is very simplified test data. Sample Data:[code="sql"]CREATE TABLE #t (LoanID VARCHAR(5), BorrowerName VARCHAR(20), BorrowerOrder INT);GOINSERT INTO #t VALUES ('::E', 'John Smith', 0) , ('::E', 'Jane Smith', 1) , ('::E', 'Rob Jackson', 2) , ('AF_CF', 'Sloan Burton', 1) , ('AF_CF', 'Virginia Burton', 2) , ('AF_CF', 'John Hardeman', 0) , ('::E', 'Mary Lamb', 4) , ('::E', 'Patrick Stewart', 3)[/code]So for loan 'AF_CF', the form should print twice:1st copy: Borrower1 = Sloan Burton, Borrower2 = Virginia Burton2nd copy: Borrower1 = John Hardeman, Borrower2 = NULLWe are on 2012, so I tried to do this with LEAD():[code="sql"]SELECT Borrower1 = BorrowerName , Borrower2 = LEAD(BorrowerName) OVER(ORDER BY BorrowerOrder)FROM #t AS tWHERE FileID = 'AF_CF'[/code]But this returns a record for every borrower, so the form is printing 3 times:1st: Borrower1 = Sloan Burton, Borrower2 = Virginia Burton2nd: Borrower1 = Virginia Burton, Borrower2 = John Hardeman3rd: Borrower1 = John Hardeman, Borrower2 = NULLI don't want that 2nd record to return. This result is what makes me think of gaps and islands, but I don't know if the 2nd record is really an island since it's (1) not stored this way...it's returning this way because of the query and (2) it's not sequential data....Finally, I tried restricting this by putting this into a CTE and then returning only the odd numbered records like I have below. This runs pretty quickly when dealing with one loan. But...I am concerned that the CTE will be slow when we run batches of loans. Attempt with CTE:[code="sql"]--With CTE;WITH cte AS (SELECT Borrower1 = BorrowerName , Borrower2 = LEAD(BorrowerName) OVER(ORDER BY BorrowerOrder) , RowNumber = ROW_NUMBER() OVER(ORDER BY BorrowerOrder)FROM #t AS tWHERE FileID = '::E')SELECT *FROM cteWHERE RowNumber % 2 = 1[/code]Is there a better, cleaner way to do this? Or is the CTE the best way to go?

Pivot query needed

$
0
0
Hi,I need some help on making the right SQL-query to get the desired results. I have a table, named tblCalls with the following tables:ID | Room | date | time | CallTypeThis tables has some data like this:1 | 11040 | 13-11-2013 | 10:00:22 | 42 | 11040 | 13-11-2013 | 11:30:55 | 43 | 11055 | 13-11-2013 | 09:22:41 | 44 | 11040 | 14-11-2013 | 15:25:16 | 4..this data needs to be presented in the following format:Room | 13-11-2013 | 14-11-201311040 | 2 | 111055 | 1 | 0 (or null)there are lots of rooms (growing number) and I need to display only the count of the last 5 days.Please help meKInd regards,

SQL Server 2012 Gotcha with Identity Column

$
0
0
We just ran across a gotcha with our SQL Server 2008 R2 to SQL Server 2012 migration.One of the applications extensively uses identity columns to provide primary keys for its data rows. Unlike SQL Server 2008 R2, SQL Server 2012 identity seeds can appear to "jump" when a failover or shutdown occurs due to the way SQL Server 2012 now caches identity column values. The "missing" identity values appear to be a "new feature" :( for SQL Server 2012:[url]http://msdn.microsoft.com/en-us/library/ms186775(v=sql.110).aspx[/url]The above link states: "Consecutive values after server restart or other failures –SQL Server might cache identity values for performance reasons and some of the assigned values can be lost during a database failure or server restart. This can result in gaps in the identity value upon insert. If gaps are not acceptable then the application should use a sequence generator with the NOCACHE option or use their own mechanism to generate key values."I presume the new sequence feature in SQL Server 2012 shares some of the database source code for identity column processing. The "create sequence" syntax allows you to turn off caching:[url]http://msdn.microsoft.com/en-us/library/ff878091.aspx[/url]I'm trying to help a Developer's reports stay "pretty" (i.e., avoid any missing key values) without causing a major rewrite of the application.Can caching be turned off for identity values in SQL Server 2012?

Combine Multiple Queries into a CTE?

$
0
0
Hello all, I am looking to build a query with a result set that combines multiple queries to appear as one result set where I can then do a calculation in a separate column in that result set. I believe I will need to use a CTE but am not sure how I can build it with multiple queries. Below is some sample data which has been refined for the concept I'm trying to achieve. [code="sql"]CREATE Table [dbo].[tempCustomerLedgerEntry]( [PostingDate] [DateTime] NOT NULL, [SalesLCY] [Decimal] (38, 20) NOT NULL, [SalespersonCode] [varchar] (20) NOT NULL, [OrderNum] [int] NOT NULL)Insert Into [dbo].[tempCustomerLedgerEntry]( [PostingDate],[SalesLCY],[SalespersonCode],[OrderNum])VALUES ( '2012-01-09', '1000.09', 'KC', '1234'),( '2012-01-19', '1109.05', 'KC', '1235'),( '2012-02-14', '5500.98', 'KC', '1237'),( '2012-03-18', '10542.88', 'KC', '1238'),( '2013-01-19', '99000.86', 'KC', '1239'),( '2013-02-15', '105000.89','KC', '1240')Select * from [dbo].[tempCustomerLedgerEntry]CREATE TABLE [dbo].[tempCreditMemo]( [PostingDate] [DATETIME] NOT NULL, [CreditAmount] [decimal](38, 20) NOT NULL, [CreditMemoNum] [Int] NOT NULL, [OrderNum] [Int] NOT NULL)Insert into [dbo].[tempCreditMemo]( [PostingDate],[CreditAmount],[CreditMemoNum], [OrderNum])VALUES ( '2012-01-09', '5.01', '8821', '1234'),( '2012-01-20', '10.00','8822', '1235'),( '2012-02-14', '200.01','8823', '1237'),( '2012-03-25', '300.10','8824', '1238'),( '2013-01-29', '100.52','8825', '1239'),( '2013-02-25', '10.99', '8826', '1240')select * from [dbo].[tempCreditMemo]CREATE TABLE [dbo].[tempSalesInvoice]( [PostingDate] [DATETIME] NOT NULL, [SaleAmount] [decimal](38, 20) NOT NULL, [SalesInvNum] [Int] NOT NULL, [OrderNum] [Int] NOT NULL)Insert into [dbo].[tempSalesInvoice]( [PostingDate],[SaleAmount],[SalesInvNum], [OrderNum])VALUES ( '2012-01-09', '1500.01', '6624', '1234'),( '2012-01-20', '1200.00','6625', '1235'),( '2012-02-14', '5750.00','6626', '1237'),( '2012-03-25', '10542.88','6627', '1238'),( '2013-01-29', '99000.86','6628', '1239'),( '2013-02-25', '105000.89', '6629', '1240')select * from [dbo].[tempSalesInvoice]select * from [dbo].[tempCreditMemo]Select * from [dbo].[tempCustomerLedgerEntry]/*Truncate table [dbo].[tempCustomerLedgerEntry]goTruncate table [dbo].[tempCreditMemo]goTruncate table [dbo].[tempSalesInvoice]go*/--Below are the result sets I am looking to combine--I will also add an additional column the performs --the calculation of Amount1-(Amount3-Amount2) as ProfitCalcselect Year(PostingDate) as PostingYear, SUM(SalesLCY) as Amount1from [dbo].[tempCustomerLedgerEntry]group by Year(PostingDate) order by Year(PostingDate) descselect Year(PostingDate) as PostingYear, SUM(CreditAmount) as Amount2from [dbo].[tempCreditMemo]group by Year(PostingDate) order by Year(PostingDate) descselect Year(PostingDate) as PostingYear, SUM(SaleAmount) as Amount3from [dbo].[tempSalesInvoice]group by Year(PostingDate) order by Year(PostingDate) desc[/code]The final result would look like the following below. [code="plain"]Posting Year Amount1 Amount2 Amount3 ProfitCalc2013 204001.75 111.51 204001.75 111.512012 18153 515.12 18992.89 -839.89[/code]Please let me know your thoughts on the best way to run such a query. Thanks.

Coin combinations

$
0
0
There's an often mentioned "problem" which is sometimes used to help in teaching kids to understand combinations, but more often just used for fun. The goal is to work out how many different amounts of money can be made up by using a non-empty subset of some given set of coins. I imagine most people will have come acoss this at least once.Recently I came across it again in a social context, and decided to write a program to solve it. SQL seemed a reasonable language to do it in. But I ran into difficulties: as far as I can tell, the recursive CTE capability in SQL isn't up to this problem. Of course it's easy to write a loop but that offends my sense of esthetics and anyway it runs like a crippled snail. Given a limiting number of coin denominations (and a limit on the number of coins of each denomination) I can write a single query to solve all instances of the problem that don't have more different denominations than that limiting number and don't have more coins than allowed. But I can't get the general solution, with no reasonable restriction on teh number of denominations or on the number of coins.I think I must be missing something - surely recursive CTEs are powerful enough to permit a general solution of this problem as a single query? Can anyone tell me how to do that?Just so you can see where I'm at, I wrapped the code to handle up to 8 denominations and up to 5000 coins of each value in a inline table-valued udf which takes a table of a defined type as a parameterbelow:-[code="sql"]/-- This code assumes that there is a database called playpen which contains a schema called play.-- It puts verious a type definition and a udf into that schema.use playpengo-- first create the type used for coin sets:create type play.coinlist as table(val int, ccount int);-- now create the UDFcreate function play.coinsums (@coins play.coinlist READONLY)returns table asreturn with tally as (select 0 as I union all select top 5000 row_number() over(order by y.object_id) from master.sys.all_objects y cross join master.sys.all_objects x), coinspad as (select * from @coins -- pad the parameter in case it has fewer than 8 rows. union all select 1000000,0 union all select 1000001,0 union all select 1000002,0 union all select 1000003,0 union all select 1000004,0 union all select 1000005,0 union all select 1000006,0 union all select 1000007,0), tempcoins as (select row_number() over (order by val) as seq, val, ccount from coinspad), A1 as (select I*val as v from tempcoins, tally where seq=1 and I between 0 and ccount), A2 as (select I*val as v from tempcoins, tally where seq=2 and I between 0 and ccount), B2 as (select distinct A1.v+A2.v as v from A1 cross join A2), A3 as (select I*val as v from tempcoins, tally where seq=3 and I between 0 and ccount), B3 as (select distinct B2.v+A3.v as v from B2 cross join A3), A4 as (select I*val as v from tempcoins, tally where seq=4 and I between 0 and ccount), B4 as (select distinct B3.v+A4.v as v from B3 cross join A4), A5 as (select I*val as v from tempcoins, tally where seq=5 and I between 0 and ccount), B5 as (select distinct B4.v+A5.v as v from B4 cross join A5), A6 as (select I*val as v from tempcoins, tally where seq=6 and I between 0 and ccount), B6 as (select distinct B5.v+A6.v as v from B5 cross join A6), A7 as (select I*val as v from tempcoins, tally where seq=7 and I between 0 and ccount), B7 as (select distinct B6.v+A7.v as v from B6 cross join A7), A8 as (select I*val as v from tempcoins, tally where seq=8 and I between 0 and ccount), B8 as (select distinct B7.v+A8.v as v from B7 cross join A8)select count(v) - 1 as answer from B8; -- subtracts one because using 0 coins is not allowedgo-- examples of using it:-declare @testlist play.coinlist;select answer from play.coinlist @testlist; -- call it with no coins, it returns 0insert @testlist(val,ccount) values(1,3),(2,2),(5,0),(10,3),(50,1); select answer from play.coinlist @testlist; -- another simple onedelete @testlist; insert @testlist(val,ccount) values(1,1),(2,5000),(5,1),(10,2),(20,1),(50,7),(100,402),(200,35);select answer from play.coinlist @testlist; -- a less simple one, with 8 rows in the parameter - the max allowed.-- I picked 8 as my maximum number of denominations because that's how many are in general us in the UK-- The UK coinage comes in units of 1,2,5,10,20,50,100 and 200 pence.insert @testlist(val,ccount) values(500,99); -- push it up to 9 rowsselect answer from play.coinlist @testlist; -- gives the wrong answer: only sees the first 8 rows in the table parameter.-- the call above gives the same answer as the one before. -- note: the UK has occassional special issues with coins which have a face value of 500 pence-- but 500 pence coins are collectors pieces, generally more valuable than 500 pence, so are not used as money.[/code]

Strange SQL Results. Example Included.

$
0
0
A coworker brought this to my attention and I can't figure out what is happening. I was hoping someone here could explain what is happening in SQL that is causing this result. The code is straight forward enough; I have modified it to use two simple temp tables.The query should return a value from table A based on the existence of a value in table B. The first select is the proper one that functions as you would expect. The second query however is throwing me off, specifically the subquery. "SELECT DISTINCT temp_int_field FROM #sub_table" is an invalid select statement but for some reason, when placed in a sub-select it not only parses, but also runs and returns data. Can someone break this down for me?I do have experience with using a WHERE NOT EXISTS as opposed to a left join and I know in these cases the sub query references the columns in the outer query so I'm guessing that something similar is happening here.[code="sql"]CREATE TABLE #temp (temp_int_field INT, temp_varchar_field VARCHAR(5))CREATE TABLE #sub_table (sub_table_int INT, sub_table_varchar VARCHAR(5))INSERT INTO #tempSELECT 1,'test'INSERT INTO #tempselect 2, 'test2'INSERT INTO #tempSELECT 3, 'test3'--//This is the sub table value that i want to return from the temp tableINSERT INTO #sub_tableselect 1, 'test2'----------------------------------->This query returns the dataset I expect; one fieldSELECT temp_int_field, temp_varchar_fieldFROM #temp WITH(NOLOCK)WHERE temp_int_field IN (SELECT sub_table_int FROM #sub_table)----------------------------------->This query returns all rows from the #temp tableSELECT temp_int_field, temp_varchar_fieldFROM #temp WITH(NOLOCK)WHERE temp_int_field IN (SELECT temp_int_field FROM #sub_table)--//Take the sub query out and make it a regular select statement and it blows up as it should.--SELECT DISTINCT temp_int_field FROM #sub_table--DROP TABLE #temp,#sub_table[/code]

How to find whether an object is used by any sp , view ?

$
0
0
How to find whether an object is used by any sp , view ?I need a query which will result the sp , view names which uses the given object name .Thanks Many

How to insert data into table from linked server

$
0
0
Hi all,I wonder if it possible to move data from tables on a linked server to a "normal database"?I am struggling with the code and can't work it out. What am I doing wrong?Maybe some extra information,Name linked server: CovasName table on linked server: tblCountriesName field: cntCountryNameName "normal" database: CovasCopyName "normal" table: Countries (or dbo.Countries)Name "normal" field: CountryThis is just a test setup. I figure that if I get this working the rest will be easier.My current query:select * from openquery(COVAS,' INSERT INTO CovasCopy.dbo.Countries(Country) SELECT cntCountryName FROM db_covas.tblCountries;')Thanks in advanceHein

Improving DELETE performance

$
0
0
Hi,in a my stored procedure I need to use a DELETE statement and I cannot use the TRUNCATE TABLE.The table source contains more tens of millions of rows and I need to eliminate some tens of millions of data.The recovery model of the db is SIMPLE.The DELETE statement is similar to this:delete from work.dbo.WRK_FACTwhere month >= @I and year = @yearAny ideas to improve the DELETE perfomances?Thanks

BCP for .xml Export Error

$
0
0
Hi All,I'm trying to export some tables from SQL Server 2012 into .xml format in a local drive and have run into a problem when reading the file in Excel for example.The code I'm currently using is:DECLARE @FileName varchar(50),@bcpCommand varchar(8000)SET @FileName = 'D:\SQLextracts\dbo.vwPOLICIES_Test'+'.xml'SET @bcpCommand = 'bcp "SELECT pvTransactionID, pvPolicyID, pvParentPolicyID, pvProductTypeName, pvClientID, pvBindRequestDate, pvEffectiveDate, pvBasePremiumAmt, pvCommissionAmount, pvAdminFee, pvStampDutyAmount, pvFireServicesLevy, pvBrokerCommission, pvBroker, pvProviderPolicyRef, pvTermExpiryDate FROM UnderwriterCENTRAL_Test.dbo.vwPOLICIES FOR XML AUTO, ROOT(''dbo.vwPOLICIES''), ELEMENTS" QUERYOUT "'SET @bcpCommand = @bcpCommand + @FileName + '" -T -c -r -t'PRINT @bcpCommandEXEC master..xp_cmdshell @bcpCommand , No_outputgoI've gone through each of the fields exported and the column pvInsuredName is what's causing the error. If I include column pvInsuredName in the script I end up with the Excel error message 'invalid file reference. the path to the file is invalid, or one or more of the referenced schemas could not be found' .I'm guessing there's an issue with some of the characters contained within the column pvInsuredName causing the error however I'm sure how to fix it.Any help is greatly appreciated.Thanks and regards,Nathan

Comma separated column output.

$
0
0
Hi There,I need a query which results the output as comma separated for example ,select name from tablename;say for example this produces the following,NameJackJohnSmithI need the follwoing,Jack,John,Smith-------------------Thanks Many

A "special" stored procedure problem

$
0
0
Hi guys! I'm not saying that actually have a problem... :-PI have this table: ID(int) | START(datetime) | STOP(datetime) lets call it DELAYSI have this input "parameters": START, STOP, STEP (in hours) the parameters to call for ex: SELECT * FROM myStorProc(START, STOP, STEP);-------------------------------------------------------------------I want to achieve the below return; with the input START: 1. october 2013 00:00 STOP: 1. october 2013 23:59 STEP: 1hHOUR(of day) | DURATION(in minutes) 0 | 10 1 | 60 2 | 41 3 | 0 .... (continue) 23 | 20====================================================The problem I'm facing; I have never worked with SQL server stored procedure and I'm kinda newbie on this section.And the 2nd problem is that for example a record in my table can start at let's say 1 and somethng and finish at 2 and something... in my case where the step is set to 1h the duration in this case cant be more than 60min... the other portion of time must be considered in the other hour ie. 2h. Also 0 (ZERO) durations must be displayed, can also happen that no delays are present for few hours :)Studyng the case the can be 4 different cases of HOUR to be aware of:1. delay start at time and finish at she same HOUR2. delay start HOUR-1 before HOUR and finish at HOUR3. -- same as 2. but opposite4. delay start BEFORE and finish AFTER HOUR... meaning the max amount possible 60 min (in case of step 1h, step 2h max will be 120min)Visually: 1 2 3 |---| |------| |------| |----------------------|Can someone be so kind and give me a draft, source code is fully requested as this will be my first stored procedure.Thanks Luka

Select Data from XML - Objects within Objects

$
0
0
I am toying with the idea of passing serialised objects to a stored procedure for the purpose of data inserts. I see this as being a way to handle multiple row inserts efficiently.However, in my limited use of XML data I am not so sure how to link the data when I have a dependency on another "object" within the serialised XML.Below is a code snippet showing what I have so far.The first insert statement works fine - but I really have no idea of how to retrieve the identifier created by the DB - I want to use an SQL statement that finds the record in the table based on the XML representation (of the PluginInfo), allowing me to insert the ConfigurationInfo with the correct reference to the PluginInfo[code="sql"] DECLARE @Config NVARCHAR(MAX) DECLARE @Handle AS INT DECLARE @TransactionCount AS INT SELECT @Config = '<ConfigurationDirectory > <ConfigurationInfo groupKey="Notifications" sectionKey="App.Customization.PluginInfo" ConfigurationKey="App.Customization.Notifications.Users.Void.AfterCore.PluginInfo" ConfigurationType="1" ConfigurationDescription="Registers plugin with GetUsers Void event" isEnabled="1"> <complexValue> <PluginInfo> <ServiceOperation>Pipeline.Users.GetUsers</ServiceOperation> <Stage>AfterCore</Stage> <PluginOrder>1</PluginOrder> <PluginTypeName>Pipeline.Users.GetUsers, Pipeline.Users</PluginTypeName> </PluginInfo> </complexValue> </ConfigurationInfo></ConfigurationDirectory>' EXEC sp_xml_preparedocument @Handle OUTPUT, @Config INSERT INTO PluginInfo ( ServiceOperation , Stage , PluginOrder , PluginTypeName ) SELECT ServiceOperation , Stage , PluginOrder , PluginTypeName FROM OPENXML (@Handle, '/ConfigurationDirectory/ConfigurationInfo/complexValue/PluginInfo', 2) WITH ( ServiceOperation NVARCHAR(100) , Stage NVARCHAR(50) , PluginOrder INT , PluginTypeName NVARCHAR(200) )-- INSERT ConfigurationInfo (columnlist) SELECT groupKey , sectionKey , ConfigurationKey , ConfigurationType , ConfigurationDescription , IsEnabled , PluginInfoId FROM OPENXML (@Handle, '/ConfigurationDirectory/ConfigurationInfo', 1) -- About Here I need to Join to the PluginInfo Table from the associated '/ConfigurationDirectory/ConfigurationInfo/complexValue/PluginInfo' node and retrieve generated Id WITH ( groupKey NVARCHAR(100) , sectionKey NVARCHAR(100) , ConfigurationKey NVARCHAR(100) , ConfigurationType NVARCHAR(100) , ConfigurationDescription NVARCHAR(500) , IsEnabled BIT , ??? )[/code]Hopefully you can understand what I'm trying to achieve here and offer some good adviceThanks
Viewing all 4901 articles
Browse latest View live