Hi all, I have a heap table [b]USER_COUNT_MONITOR[/b] with a single column [b]ID[/b] and DISTINCT values from 1 to 100000 (Total records = 100000). Now I'm trying to fetch 2nd highest value using these two queries:1. [size="1"]Select ID from USER_COUNT_MONITORorder by ID descoffset 1 rowfetch next 1 rows only[/size]2. [size="1"]SELECT MAX(ID)FROM USER_COUNT_MONITORWHERE ID < (SELECT MAX(ID) FROM USER_COUNT_MONITOR)[/size][b]I/O Stats are as below:[/b]Query 1. Table 'user_count_monitor'. Scan count 1, logical reads 489.Query 2. Table 'user_count_monitor'. Scan count 2, logical reads 978.I/O stats clearly show that 1st query is performing 2 times better then 2nd query. But execution plan shows that 2nd query is performing 80% better then 1st query.[b]Now, I create this index on the table :[/b][i]CREATE NONCLUSTERED INDEX [test_idx] ON [dbo].[user_count_monitor] ([id])[/i][b]New I/O Stats are as below:[/b]Query 1. Table 'user_count_monitor'. Scan count 1, logical reads 2. Query 2. Table 'user_count_monitor'. Scan count 2, logical reads 176.New I/O stats still shows that 1st query is performing much better then 2nd query. But now, new execution plan show that 1st query is performing 95% better then 2nd query.[b]In both cases, I/O stats are giving almost same picture, But execution plan is totally different.Does it mean that we can't depend on execution plan for performance !!! [/b]Regards,Ashish
↧
Can't we rely on execution plan for performance !!!
↧
EST TO UTC
HiI have to create offset to convert my EST Datetime columns to UTC to compare with Utc datetime columns.The server local time follows UTC timing .I read few forums and few people suggested[i] @offset = DATEDIFF(HH,GETUTCDATE(),GETDATE()). [b][/b][/i]this one would not work on my server as my server localtime = utc time.So,I cannot obtain offset using the above method.Is there anyway you think I can convert my est datetime columns to utc considering daylight constraint.RegardsS
↧
↧
Help On Query
CREATE TABLE [dbo].[tmp]([msisdn] varchar(20) ) DECLARE @intFlag bigINTSET @intFlag = 15210000000WHILE (@intFlag <=15219999999)BEGINPRINT @intFlaginsert into tmp select @intFlag set @intFlag= @intFlag + 1 ENDGOIs there any short way to perform this
↧
Trigger Issue...
Hi,I've a table that has a trigger for insert that executes the flowing statement:[code="sql"]UPDATE ArtigoArmazem SET QtReservada = 0 FROM INSERTED I INNER JOIN LInhasdoc LD ON i.IdLinhasDoc = LD.Id WHERE ArtigoArmazem.Artigo = LD.Artigo[/code]The table ArtigoArmazem also has a trigger for update that initially had a cursor to update stocks quantities but I changed it to a "simple" UPDATE:[code="sql"]-- OLD TRIGGERALTER TRIGGER [dbo].[GCP_STK_ArtigoArmazem_UPD] ON [dbo].[ArtigoArmazem] FOR UPDATEASSET NOCOUNT ONDECLARE @Artigo AS VARCHAR(50)DECLARE @StkActual AS FLOATIF UPDATE(StkActual) BEGIN DECLARE curRegistos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR SELECT Artigo, StkActual FROM Deleted WHERE StkActual <> 0 OPEN curRegistos FETCH NEXT FROM curRegistos INTO @Artigo, @StkActual WHILE @@FETCH_STATUS = 0 BEGIN EXEC GCP_STK_ActualizaArtigo 'R', @Artigo, @StkActual FETCH NEXT FROM curRegistos INTO @Artigo, @StkActual END CLOSE curRegistos DEALLOCATE curRegistos DECLARE curRegistos CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR SELECT Artigo, StkActual FROM Inserted OPEN curRegistos FETCH NEXT FROM curRegistos INTO @Artigo, @StkActual WHILE @@FETCH_STATUS = 0 BEGIN EXEC GCP_STK_ActualizaArtigo 'I', @Artigo, @StkActual FETCH NEXT FROM curRegistos INTO @Artigo, @StkActual END CLOSE curRegistos DEALLOCATE curRegistos ENDGO---- The SP GCP_STK_ActualizaArtigo just does an UPDATE on @Artigo and sets StkActual to StkActual + @StkActual if 'I' or StkActual - @StkActual id 'D'----- NEW TRIGGER----CREATE TRIGGER [dbo].[GCP_STK_ArtigoArmazem_UPD] ON [dbo].[ArtigoArmazem] FOR UPDATEASBEGINSET NOCOUNT ON IF UPDATE(StkActual) BEGIN ;WITH res AS ( SELECT Artigo, -StkActual AS StkActual FROM DELETED WHERE StkActual <> 0 UNION ALL SELECT Artigo, StkActual FROM INSERTED ), res1 AS ( SELECT Artigo, SUM(StkActual) Stk FROM res GROUP BY Artigo ) UPDATE Artigo SET STKActual = STKActual + res1.Stk FROM res1 WHERE MovStock = 'S' AND Artigo.Artigo = res1.artigo ENDEND[/code]When I run a trace to see what's happening I get with the OLD trigger a duration of half the new trigger and 900 reads vs 4900 reads with the new trigger!!!If I insert a RETURN statement just at the beginning of the new trigger the results are the same but if I let the RETURN and remove the rest of the SQL the result is the same as the old trigger.What can be causing this? The trigger's code shouldn't even be executed case UPDATE(stkActual) is false...Thanks,Pedro
↧
Creating a Database
I am having trouble creating my first database file. Here is the syntax used:CREATE DATABASE AccountingON (NAME = 'Accounting', FILENAME = 'C:\Program Files\Microsoft SQL SERVER\MSSQL10.SQLEXPRESS\MSSQL\DATA\AccountingData.mdf',SIZE = 10,MAXSIZE = 50,FILEGROWTH = 5)LOG ON(NAME = 'AccountingLog',FILENAME = 'C:\Program Files\Microsoft SQLServer\MSSQL10.SQLEXPRESS\MSSQL\DATA\AccountingLog.ldf',SIZE = 5MB,MAXSIZE = 25MB,FILEGROWTH = 5MB);GOAnd I get an error message when executed:Msg 5133, Level 16, State 1, Line 1Directory lookup for the file "C:\Program Files\Microsoft SQL SERVER\MSSQL10.SQLEXPRESS\MSSQL\DATA\AccountingDat a.mdf" failed with the operating system error 123(The filename, directory name, or volume label syntax is incorrect.).Msg 1802, Level 16, State 1, Line 1CREATE DATABASE failed. Some file names listed could not be created. Check related errors.I have double checked my file name path, I have removed spaces in the syntax, added underscores, and changed the folder from MSSQL10.SQLEXPRESS to MSSQL11.TSQLLAB as that is where my adventure works database is. I keep getting the same error and cannot figure out why this isn't working, when the directory path is correct and has been verified multiple times. Can someone please help me figure out what I am missing?Also, the book I am using covers SQL Server 2008, however I am using SQL Server 2012 Express. Not sure if the Syntax is different from 2008 to 2012.
↧
↧
Shift Column values to the left
I am trying to clean up some data in one of the tables in our database. The table consists of an ID column and a 3 columns that contains alternative names. Each ID is allowed to have a maximum of 3 alternative names. If there are 3 names present then AlternativeName1, AlternativeName2, AlternativeName3 should be filled. If there are 2 names present then AlternativeName1 and AlternativeName2 should be filled. If 1 name is present then AlternativeName1 should be filled.Currently the alternative Names fields are filled in haphazardly. For example if the is one alternative name is provided it can be found in the AlternativeName2 or AlternativeName3 column. I would like update the table so that it follows the order presented above. I have provided some data below to illustrate what is required.[code="sql"]--Test TableCREATE TABLE #TEST([ID] INT IDENTITY(1,1) PRIMARY KEY NOT NULL,[AlternateName] nvarchar(20) NUll,[AlternateName1] nvarchar(20) NUll,[AlternateName2] nvarchar(20) NUll)--Load Table with test data INSERT INTO #TEST( [AlternateName] , [AlternateName1] , [AlternateName2] )SELECT 'Micheal','Mickey','' UNION ALLSELECT '','James','Jimmy' UNION ALLSELECT '','','Sarah' UNION ALLSELECT 'Peter','','Pete' UNION ALLSELECT 'Andrew','Andy','Andre' UNION ALLSELECT '','John'SELECT * FROM #TEST--The output should beID AlternateName AlternateName1 AlternateName2 1 Micheal MIckey2 James Jimmy3 Sarah4 Peter Pete5 Andrew Andy Andre6 John[/code]Any Ideas?
↧
Pivot EDI EAV type table
Hi all-I'm trying to flatten this table into something like the second table. Any suggestions would be greatly appreciated.NickSee the attached table in Excel.Entity | Attribute | Value | PositionOrderInFileNum ISA ISA06 451294709 1ISA ISA08 USBBBBBBQ 2GS GS02 451294709 3GS GS03 364265323 4ST ST02 12 5ST ST03 005010X218 6ST ST02 13 7ST ST03 005010X218 8GS GS02 777294709 9GS GS03 364265323 10ST ST02 1 11ST ST03 005010X218 12ST ST02 2 13ST ST03 005010X218 14Into a flat table like this (Grouped by GS and ST ):ISA6 | ISA8 | GS02 | GS03 | ST01 | ST02
↧
Want to add Text data
Hi All,I have table called T1 where the data is populated like belowLineNumber errortext Fileid1 a 101 b 102 a 112 b 112 c 113 c 123 d 12Now I have a table called t2 with same structure. Now I want to insert the records into t2 table and the data should be coming from T1 table. where the id is same it will take one id and one linenumber and concatenate of errortext field. My output will be like belowLineNumber errortext Fileid1 a,b 102 a,b,c 113 c,d 12File id should be taken once and then distinct of linenumber field and then concatenate of errortext field.Thanks in advance for your help!!
↧
Beginners Question on Table-Valued Functions
Based on what I read about Table-Valued Functions it can be used to return modified data from one or more tables in a database. But since they are programmable functions, they can also generate data. Does this mean Table-Valued Functions can be created to prevent applications from accessing tables directly while still providing access to retrieve or modify data?:doze:
↧
↧
Optimize TSQL
Hi Please optimze below Query [code="sql"]select A.SRC_STM_CD , C.PROD_CD ,c.PROD_DESC ,d.PROD_CLASS ,d.PROD_CLASS_DESC ,e.CURRENCY ,e.FX ,count(*) , sum(value(B.RECON_BAL,0)) RECON_BAL ,sum(value(o.OUTSTANDING_BAL,0)) ,sum(value(n.NTNL_AMT,0)) from ( select RI.ri_id , RI.src_stm_id , cl_code SRC_STM_CD from trgisl.RI RI , trgisl.cl CL where RI.src_stm_id = CL.cl_id ) A,( select R.ri_id , CL.CL_CODE as PROD_CD ,CL.dsc as PROD_DESC from trgisl.cl CL , trgisl.ri R , trgisl.ri_x_cl RX where R.ri_id = RX.ri_id and RX.cl_id = CL.cl_id ------ and ri_x_cl_tp_id = 21167 ) C ,( select R.ri_id , CL.CL_CODE as PROD_CLASS ,CL.dsc as PROD_CLASS_DESC from trgisl.cl CL , trgisl.ri R , trgisl.ri_x_cl RX where R.ri_id = RX.ri_id and RX.cl_id = CL.cl_id and ri_x_cl_tp_id = 21166 ) d ,( select R.ri_id , CL.CL_CODE CURRENCY ,g.FIRST_RT as FX from trgisl.cl CL , trgisl.ri R , trgisl.ri_x_cl RX , trgisl.gl_recon_cur g where R.ri_id = RX.ri_id and RX.cl_id = CL.cl_id and ri_x_cl_tp_id = 21161 and g.cURR_CD=cL.CL_code and g.msr_dt = '2013-04-30' ) e,( select R.ri_id , AU.unq_id_src_stm GL_ACCOUNT_ID from trgisl.ri R , trgisl.ri_x_au RX LEFT OUTER JOIN trgisl.au AU on RX.au_id = AU.au_id where R.ri_id = RX.ri_id and ri_x_au_tp_id = 1268) G,( select R.ri_id , OU.BR_NO TRANSIT from trgisl.ri R , trgisl.RI_X_IP RX LEFT OUTER JOIN trgisl.OU OU on RX.ip_id = OU.ou_ip_id where R.ri_id = RX.ri_id and ri_x_ip_tp_id = 21145 ) T,( select R.ri_id , RV.val_amt NTNL_AMT from trgisl.ri R , trgisl.ri_val RV where R.ri_id = RV.ri_id and ri_val_tp_id= 21175 ) N,( select R.ri_id , AB.pst_amt OUTSTANDING_BAL from trgisl.ri R , trgisl.ri_x_au RX , trgisl.au_bal AB where R.ri_id = RX.ri_id and RX.au_id = AB.au_id and ri_x_au_tp_id = 1267 and AB.pnt_bal_tp_id=31173 ) O,( select R.ri_id , AB.pst_amt RECON_BAL from trgisl.ri R , trgisl.ri_x_au RX , trgisl.au_bal AB where R.ri_id = RX.ri_id and RX.au_id = AB.au_id and ri_x_au_tp_id = 1267 and AB.pnt_bal_tp_id=1264 ) Bwhere A.ri_id = C.ri_id and A.ri_id = B.ri_id and A.ri_id = G.ri_id and A.ri_id=d.ri_id and A.ri_id=e.ri_id and A.ri_id=T.ri_id and A.ri_id=n.ri_id and A.ri_id=O.ri_idand e.CURRENCY is not null and T.TRANSIT is not nulland G.GL_ACCOUNT_ID is not nulland e.CURRENCY <>'' and T.TRANSIT <>''and G.GL_ACCOUNT_ID <>''group by A.SRC_STM_CD , C.PROD_CD ,c.PROD_DESC ,d.PROD_CLASS ,d.PROD_CLASS_DESC ,e.CURRENCY ,e.FX [/code]
↧
Invalid object name 'sys.spt_values'
Sql 2012 Enterprise installation. user databases are all fine. Managing objects in management studio doesn't work. We know an application wrote its tables into the master database by mistake. I found the utables.sql script which will recreate the master database views, but it fails because it can't find sys.spt_values[color=#FF0000]Invalid object name 'sys.spt_values' [/color]I have backups of master but was hoping this script would work.create view spt_values asselect name collate database_default as name, number, type collate database_default as type, low, high, statusfrom sys.spt_valuesgo
↧
How to search using stored procedure
Hello Word and Hello all pipzGood Day!!!I need some advice on how to search using stored procedure...I have 3 tables namely Bio, Sex and Status*BiobioIDfirstnamemiddlenamelastnamesexIDstatusID*SexsexIDsex(male or female only)*StatusstatusIDstatus(Single, Married or devorce only)I want to search Firstname, Middlename, Lastname, sex and status.what should i do?...thanks hoping for a reply :-)this is my UI (Please see my attachment, please be guided accordingly..thanks)
↧
108,000,000 row table - check for matches
Good afternoon,Long time reader - first time poster here! I am currently working on a 108m row table where some of the ids (TOID column) have inadvertently been shortened - they should all be 16chars in length, i.e. 0001000000076579000100000010456600010000001592250001000000250870000100000026372200010000003033050001000000303309but some are 13 in length. I think that some are missing a 100 at the beginning and some are missing 500. I have an update table (where I have to find matches between this table and the big daddy table based on this id (called TOID))I need to find out which rows in the update table don't match rows in the big daddy table - I can join on the matches, no problem, but when it comes to searching for those matches which are a concatenation of 100/500<TOID> this makes the query run very very slowly.my code is quite simply:UPDATE DUNCANTEMPSET DOESEXIST = 1WHERE EXISTS (SELECT TOID FROM [OS_MasterMap].dbo.OS_MM_AREA OMA WITH (NOLOCK) WHERE ('500' + OMA.Toid = DUNCANTEMP.TOID OR '100' + OMA.Toid = DUNCANTEMP.TOID) AND len(OMA.Toid) = 13)Where DUNCANTEMP consists of:CREATE TABLE dbo.DUNCANTEMP( TOID VARCHAR(50) NULL, DOESEXIST INT NULL) ON [PRIMARY]The tables area static and in a dev environment.And [OS_MasterMap].dbo.OS_MM_AREA has loads of columns, but TOID is the only one we need to look at:CREATE TABLE dbo.OS_MM_AREA( OBJECTID INT IDENTITY, SHAPE GEOMETRY NOT NULL, Toid NVARCHAR(20) NOT NULL, Version INT NULL, VerDate DATETIME NULL, FeatCode INT NULL, Theme NVARCHAR(80) NULL, CalcArea NUMERIC(38, 8) NULL, Change NVARCHAR(80) NULL, DescGroup NVARCHAR(150) NULL, DescTerm NVARCHAR(150) NULL, Make NVARCHAR(20) NULL, PhysLevel INT NULL, PhysPres NVARCHAR(20) NULL, Broken SMALLINT NULL, LoadDate DATETIME NULL, CONSTRAINT PK__OS_MM_AR__F4B70D851D5924B0 PRIMARY KEY (OBJECTID), CONSTRAINT UQ__OS_MM_AR__FF378992EC7F35C5 UNIQUE (Toid)) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]GOThere is a unique constraint on OS_MM_AREA (TOID) and a non-clustered index.there is a clustered index on TOID on the DUNCANTEMP table (but not unique as there may be some duplicate TOIDs based on multiple update rows).My question is: my code has been running for about 14hrs now.. there are 33934 rows in Duncantemp and 107913558 rows in the OS_MM_AREA table - my code will be scanning the big table for matches for each row..can anyone think of a better and quicker way of finding those rows in DUNCANTEMP which don't match any records in OS_MM_AREA given a direct match or +100/+500<TOID> match as well?I welcome suggestions please.(if it doesn't complete over the weekend, I will add 2 more columns to the big daddy table with +500 and +100<TOID>, index them, and run the code using a join.. but I was interested if I had fundamentally missed something firstthank you kindlyD.
↧
↧
Build menu with CTE ....
Hi,I've a menu that has several levels and each level has a position to order the entries.We had a cursor, recursive, that built the menu but we'd decided to change it to CTE since it's faster.Here is a sample of the structure and data:[code="sql"]IF EXISTS (SELECT 1 FROM sys.objects WHERE name = 'menu') DROP TABLE menuGOCREATE TABLE menu (Id TINYINT NOT NULL, IdRoot TINYINT NULL, Name VARCHAR(10) NOT NULL, Position TINYINT NOT NULL)GOINSERT INTO menu (Id, idRoot, Name, Position) VALUES (1, 0, '0', 1), (4, 1, '1', 1), (2, 1, '2', 2), (3, 2, '2.1', 1), (6, 3, '2.1.1', 1), (8, 6, '2.1.1.1', 1), (5, 2, '2.2', 2), (9, 2, '2.3', 3), (7, 1, '3', 3)GOWITH menuCTE (Id, IdRoot, Name, Position, Ord) AS ( SELECT Id, IdRoot, Name, Position, 0 FROM menu WHERE IdRoot = 0 UNION ALL SELECT m.Id, m.IdRoot, m.Name, m.Position, mCTE.Ord + 1 FROM menu m INNER JOIN menuCTE mCTE ON m.IdRoot = mCTE.Id)SELECT * FROM menuCTE [/code]The SELECT output is:[code="plain"]Id IdRoot Name Position Ord---- ------ ---------- -------- -----------1 0 0 1 04 1 1 1 12 1 2 2 17 1 3 3 13 2 2.1 1 25 2 2.2 2 29 2 2.3 3 26 3 2.1.1 1 38 6 2.1.1.1 1 4[/code]I've tried several ORDER BY and even ROW_NUMBER PARTITION BY but can't seem to find the right combination....The output desired, and obtained with the recursive cursor, is:[code="plain"]Id IdRoot Name Position Ord---- ------ ---------- -------- -----------1 0 0 1 04 1 1 1 12 1 2 2 13 2 2.1 1 26 3 2.1.1 1 38 6 2.1.1.1 1 45 2 2.2 2 29 2 2.3 3 27 1 3 3 1[/code]Help please...Thanks,Pedro
↧
SSRS - Number formatting
Hi, I am using the following custom format "#,##0.00% ;(#,##0.00%)" in my SSRS numeric column and Color code :- IIF(COl.value < 0 , "Red" , "Black"However, When the data is displayed so values are 0.00 , [color=#FF0000](0.00)[/color],[color=#FF0000]0.00[/color]I am unable to understand why [color=#FF0000]0.00[/color] are coming.Please suggest.
↧
Replication
Hello, good, I'm Brazilian and I'm not very good English, I apologize.I have a problem before replication when replicating tables I wanted to set some rules for some columas not be replicated, or be replicated with a default value.[quote]id | descrisaoProduto | estoque1 | abcd | 10[/quote]on replication[quote]id | descrisaoProduto | estoque1 | (null or value default) | 10[/quote]And find out if there is any way that when it is replicated, it convert a table to another.[quote]id | estoqueLocal | estoqueMatriz1 | 10 | 0[/quote]on replication[quote]Filial: (replicação através da matrizid | estoqueLocal | estoqueMatriz1 | 0 | 10[/quote]Tanks :-)
↧
Trying to build a report menu from data stored in two tables in SQL Database
I have two separate tables in my database ReportCategories and Reports. I am trying to determine how I can pull a listing of all the report categories that are ancestors of the reports which can be displayed by the user. (Some users will be able to see all reports, and some users will only be able to see a sub-set of the available reports. I want to build the report menu on a per-user basis in my program. If the user cannot see any of the reports in a particular category, I do not want that category to be displayed.) If this cannot be done from T-SQL, I can implement this in the program logic, but it seems like this should be possible to query from the database. Any help would be appreciated!Sample Table Structure:[code="sql"]CREATE TABLE [dbo].[tblTestCategories]( [ID] [int] NOT NULL, [CategoryName] [varchar](50) NOT NULL, [ReportCategoryID] [int] NULL, CONSTRAINT [PK_tblTestCategories] PRIMARY KEY CLUSTERED ([ID] ASC))GOALTER TABLE [dbo].[tblTestCategories] ADD CONSTRAINT [DF_Table_1_ReportName] DEFAULT ('') FOR [CategoryName]GOALTER TABLE [dbo].[tblTestCategories] WITH CHECK ADD CONSTRAINT [FK_tblTestCategories_tblTestCategories] FOREIGN KEY([ReportCategoryID])REFERENCES [dbo].[tblTestCategories] ([ID])GOALTER TABLE [dbo].[tblTestCategories] CHECK CONSTRAINT [FK_tblTestCategories_tblTestCategories]GO[/code][code="sql"]CREATE TABLE [dbo].[tblTestReports]( [ID] [int] NOT NULL, [ReportName] [varchar](50) NOT NULL, [CategoryID] [int] NULL)GOALTER TABLE [dbo].[tblTestReports] ADD CONSTRAINT [DF_tblTestReports_ReportName] DEFAULT ('') FOR [ReportName]GOALTER TABLE [dbo].[tblTestReports] WITH CHECK ADD CONSTRAINT [FK_tblTestReports_tblTestCategories] FOREIGN KEY([CategoryID])REFERENCES [dbo].[tblTestCategories] ([ID])GOALTER TABLE [dbo].[tblTestReports] CHECK CONSTRAINT [FK_tblTestReports_tblTestCategories]GO[/code]Sample Data:[code="sql"]INSERT INTO [dbo].[tblTestCategories] ([ID], [CategoryName], [ReportCategoryID])SELECT 1, 'Test Category 1', NULLUNION ALLSELECT 3, 'Test Sub Category 1', 1UNION ALLSELECT 2, 'Test Category 2', NULLUNION ALLSELECT 5, 'Test Sub Category 2', 2UNION ALLSELECT 7, 'Test Category 3', NULLUNION ALLSELECT 6, 'Test Sub Category 3', 7UNION ALL SELECT 8, 'Test Sub Sub Category 3', 6UNION ALL SELECT 4, 'Test Sub Sub Sub Category 3', 8UNION ALLSELECT 10, 'Test Category 4', NULLUNION ALL SELECT 11, 'Test Category 5', NULLUNION ALL SELECT 9, 'Test Sub Category 5', 11GO[/code][code="sql"]INSERT INTO [dbo].[tblTestReports] ([ID], [ReportName], [CategoryID])SELECT 1, 'Report 1', 1UNION ALLSELECT 2, 'Report 2', NULLUNION ALLSELECT 3, 'Report 3', 2UNION ALLSELECT 4, 'Report 4', 3UNION ALLSELECT 5, 'Report 5', 4UNION ALLSELECT 6, 'Report 6', 5UNION ALLSELECT 7, 'Report 7', 7UNION ALLSELECT 8, 'Report 8', 7UNION ALLSELECT 9, 'Report 9', 1UNION ALLSELECT 10, 'Report 10', NULLUNION ALLSELECT 11, 'Report 11', NULLUNION ALLSELECT 12, 'Report 12', 8UNION ALLSELECT 13, 'Report 13', NULLUNION ALLSELECT 14, 'Report 14', NULLUNION ALLSELECT 15, 'Report 15', 9UNION ALLSELECT 16, 'Report 16', NULLUNION ALLSELECT 17, 'Report 17', NULLUNION ALLSELECT 18, 'Report 18', NULLUNION ALLSELECT 19, 'Report 19', NULLUNION ALLSELECT 20, 'Report 20', NULLGO[/code]I have been able to use the following query (using a CTE) to order all the categories together, but I have not been able to determine a way to join the reports table to this to limit the return to only categories with a report descendant:[code="sql"]WITH ReportCategoryList AS (SELECT *, 1 AS CategoryLevel FROM tblTestCategories WHERE ReportCategoryID IS NULLUNION ALLSELECT TC.*, RCL.CategoryLevel + 1 FROM tblTestCategories AS TC INNER JOIN ReportCategoryList RCL ON TC.ReportCategoryID = RCL.ID WHERE TC.ReportCategoryID IS NOT NULL)SELECT * FROM ReportCategoryList RCL ORDER BY RCL.CategoryLevel, RCL.ID[/code]What should happen is that I should be able to pull a listing of the report categories, NOT including [quote]Test Category 4[/quote], as that is the only report category (or sub-category), that does not have at least 1 report as a descendant.If you need more clarification, let me know and I will do my best to try to clarify what I am looking for:crazy:
↧
↧
Converting Access Function in SQL Function, Help
helloI'm trying to convert an Access function into a SQL function and having a litlte problem with the syntax. Hopefully someone can point me in the right direction.Below is the VB function from Access.[code="vb"]If [vType] = "618" Or [vType] = "617" Then Select Case vGrade Case "DS*" [Points] = 180 Case "DS" [Points] = 150 Case "ME" [Points] = 105 Case "PA" [Points] = 45 Case "FL" [Points] = 0 Case Else [Points] = Null End SelectEnd If If [vType] = "622" Or [vType] = "623" Then Select Case vGrade Case "D*D*" [Points] = 360 Case "D*D" [Points] = 330 Case "DD" [Points] = 300 Case "DM" [Points] = 240 Case "MM" [Points] = 180 Case "MP" [Points] = 120 Case "PP" [Points] = 60 Case "FL" [Points] = 0 Case Else [Points] = Null End SelectEnd If If [vType] = "262" Then Select Case vGrade Case "DS*" [Points] = 180 Case "DS" [Points] = 150 Case "ME" [Points] = 105 Case "PA" [Points] = 45 Case "FL" [Points] = 0 Case Else [Points] = Null End SelectEnd If[/code]I have started creating the function but running into the syntax problems.[code="sql"]SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGO CREATE FUNCTION dbo.tf_Points(@Grade AS VARCHAR(10), @Type AS INT)IF @Type >0 BEGIN SELECT CASE WHEN @Type = '618' Or @Type = '617' AND @Grade = 'DS*' THEN 180 WHEN @Type = '618' Or @Type = '617' AND @Grade = 'DS' THEN 150 WHEN @Type = '618' Or @Type = '617' AND @Grade = 'ME' THEN 105 WHEN @Type = '618' Or @Type = '617' AND @Grade = 'PA' THEN 45 WHEN @Type = '618' Or @Type = '617' AND @Grade = 'FL' THEN 0 ELSE NULL END RETURNENDELSE [/code]Or if there is a more efficient way of doing this, I'd welcome any ideas :)
↧
script - growing database.
Friends,someone could share with me a script that calculates the growth of a database and store on table? weekly and monthly?
↧
Reg : Help on Transactions in SQL
Hi There,I have some doubts on transactions. Following is my problem & I'm intended to go with transactions . I have a stored procedure. If it ran successfully then no problem, in case of any interruption like killing the SP or some error occurred while in the middle of the run then I have to rollback all the things which was done by sp so far. So I'm intended to go with transactions . If I create transaction it will make the roll back easy to me.1. I need code which will automatically rollback when any error while in the run of whole SP.2. What would happen if the sp killed forcibly .i.e., will transaction commuted or rolled back ?Thanks in Advance
↧