Wednesday, August 28, 2013

[T-SQL] Wrong datatype for SP?

[T-SQL] Wrong datatype for SP?


Wrong datatype for SP?

Posted: 28 Aug 2013 12:56 AM PDT

When I try to execute a SP as shown below:EXEC eusp_e5_eSM_AS01_MaterialItemContainerlabelReport 'MC-00000002-13-0001','MC-00000002-13-0002'The following error message is shown:Msg 8144, Level 16, State 2, Procedure eusp_e5_eSM_AS01_MaterialItemContainerlabelReport, Line 0Procedure or function eusp_e5_eSM_AS01_MaterialItemContainerlabelReport has too many arguments specified.I guess the error is due to wrong dataype of SP parameter. The code is below:ALTER PROCEDURE [dbo].[eusp_e5_eSM_AS01_MaterialItemContainerlabelReport]@containerCodes nvarchar(MAX)What should this nvarchar(MAX) be changed to accommodate the comma seprated values?

scripting in table

Posted: 27 Aug 2013 07:13 AM PDT

hithis is my tableCREATE TABLE [dbo].[emp_new]( [empid] [int] NULL, [primary1] [varchar](20) NULL, [primaryinten1] [int] NULL, [primary2] [varchar](20) NULL, [primaryinten2] [int] NULL, [primary3] [varchar](20) NULL, [primaryinten3] [int] NULL, [primary4] [varchar](20) NULL, [primaryinten4] [int] NULL, [primary5] [varchar](20) NULL, [primaryinten5] [int] NULL, [primary6] [varchar](20) NULL, [primaryinten6] [int] NULL, [primary7] [varchar](20) NULL, [primaryinten7] [int] NULL) ON [PRIMARY]---------------------------------------------------------insert into emp_new(empid,primary1,primaryinten1)values(1,'ws',1)insert into emp_new(empid,primary2,primaryinten2)values(1,'gh',1)insert into emp_new(empid,primary2,primaryinten2)values(1,'lg',3)insert into emp_new(empid,primary2,primaryinten2)values(1,'fd',1)insert into emp_new(empid,primary2,primaryinten2)values(1,'hj',1)----------------------------------------------------------------------empid primary1 primaryinten1 primary2 primaryinten2 primary3 primaryinten3 primary4 primaryinten4 primary5 primaryinten5 primary6 primaryinten6 primary7 primaryinten71 ws 1 NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL1 NULL NULL gh 1 NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL1 NULL NULL lg 3 NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL1 NULL NULL fd 1 NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL1 NULL NULL hj 1 NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL----------------------------------------------------------------------------------------whati want is everything in 1 line.empid primary1 primaryinten1 primary2 primaryinten2 primary3 primaryinten3 primary4 primaryinten4 primary5 primaryinten5 primary6 primaryinten6 primary7 primaryinten71 ws 1 gh 1 lg 3 fd 1 hj 1 null null null null------------------------------------------------------------------------------------------and the rows rows should be delete.there should be line where primary1 is not null ,that line should be filled with all other condition and other rows should be delete.how to do it

Query Help

Posted: 27 Aug 2013 11:39 AM PDT

HiI have a requirement like below. I have to give the flavours to the application.We have thousands of records to update.Please help me. Actual tableAPP|||COLOUR|||FLAVOURap1|||GREEENap1|||YELLOWap1|||YELLOWap1|||GREEENap2|||YELLOwap2|||YELLOWap2|||YELLOWap3|||GREEENap3|||YELLOWap3|||RED ap3|||GREEENap4|||GREENap4|||GREENap4|||GREENOutput would look like belowAPP|||COLOUR|||FLAVOURap1|||GREEEN|||YELLOWAap1|||YELLOW|||YELLOWAap1|||YELLOW|||YELLOWAap1|||GREEEN|||YELLOWAap2|||YELLOW|||YELLOWBap2|||YELLOW|||YELLOWBap2|||YELLOW|||YELLOWBap3|||GREEEN|||REDap3|||YELLOW|||REDap3|||RED |||REDap3|||GREEEN|||REDap4|||GREEN|||GREENAap4|||GREEN|||GREENAap4|||GREEN|||GREENAlet me know if you need additional informationThanksAswin

Is there a way to sort the table after records are inserted?

Posted: 27 Aug 2013 09:33 PM PDT

Is there a way to sort the table after records are inserted?Declare @tab Table(name varchar(10), value varchar(10))Declare @mystring varchar(10)set @mystring='AA'insert into @tab select 'A', 1 unionselect 'AA',2select @mystring=REPLACE(@mystring,name,value) from @tab order by LEN(name) descselect @mystringHere is my problem1. I create a table with two cols Name and Value2. I insert records into this table using a union statement. (Ex records : {A,1},{AA,2})3. Now I have a string which I need to be replaced. Ex: if my string is AA, I need it to be replaced by 2. But now what happen is since in the table A is before AA, it replaces it with two 1's , ie 11

Insert on condition in Trigger

Posted: 27 Aug 2013 04:51 PM PDT

Hi,Here is the code that I have written and its working fine. But now I have to put a condition while Insertion and I am not getting how to do that.Scenario is: Currently if made any changes DeviationRequestDetails a new row gets inserted into CLCProcessUnitDetailsCompany if it not exists previously. But now what I want is that if I made any change in column DeviationStatus of Source then only new rows should get inserted in Target else if changes made in any other column of Source then no rows should get inserted into Target.Hope the scenario is clear to you now....[code="sql"]ALTER Trigger [dbo].[Trg_DeviationRequestDetails_Ins]ON [dbo].[DeviationRequestDetails]After INSERT, UPDATE ASBEGIN Declare @deviationstatus int SET @deviationstatus = (SELECT D.DeviationStatus from DELETED D) MERGE INTO CLCProcessUnitDetailsCompany T USING INSERTED as S ON S.ProjectID = T.ProjectID AND S.ProposalID = T.ProposalID AND S.SolutionId = T.SolutionId AND S.UnitID = T.UnitID WHEN MATCHED AND S.DeviationStatus <> @deviationstatus THEN UPDATE SET T.DevDateChanged = Getdate() WHEN NOT MATCHED THEN INSERT ( ProjectID, ProposalID, SolutionID, UnitID, DevDateChanged, QuotDateChanged, ApprovalDateChanged, AddedBy, DateAdded, ChangedBy, DateChanged ) VALUES ( S.ProjectID, S.ProposalID, S.SolutionID, S.UnitID, Getdate(), NULL, NULL, S.AddedBy, S.DateAdded, S.ChangedBy, S.DateChanged );END[/code]

Difficult Sorting

Posted: 27 Aug 2013 07:35 AM PDT

Using SQL Server 2008 R2, but also have access to SQL Server 2012I have this sample data.[b][u]ItemNo[/u][/b] [b][u]DueDate[/u][/b] [b][u]Cham[/u][/b]121117 2013-09-05 121098 2013-09-05 Y333456 2013-09-07 Y347545 2013-09-07798665 2013-09-07 982389 2013-09-08 908465 2013-09-08 Y985551 2013-09-09 Y432568 2013-09-09 874378 2013-09-10647849 2013-09-10098357 2013-09-10673467 2013-09-13098355 2013-09-13 Y237678 2013-09-13 Y984474 2013-09-17 Y093409 2013-09-17003434 2013-09-18The first sort must be on "Due Date". The second sort must be on "Cham". When days are spanned, I want to have the Cham field as continuous as possible. I realize this will not be possible for every day span. It seems the Cham field must be sometimes sorted Asc and other times sorted Desc.Thanks.

Controlling Transaction log size in Simple Mode

Posted: 27 Aug 2013 06:53 PM PDT

Never really got to grips with Transaction log size in Simple Recovery mode. I originally had a MERGE statement within a stored procedure. When this ran it looked at a table with approx 100 m records as source and the target was a table of the same size. When running this we found the transaction log file grew and we ran out of space.The first solutionWe split the stored procedure into two MERGE statements. The MERGE's do inserts and updates only. I split it into two in the hope that once the first statement completes then the second would reuse the space in the transaction log. So Log siize would increase when executing the first statement. When statement one completes and statement two starts the transaction log would reuse the space it had assigned to statement one.This did not appear to work. The log kept growing. Now looked at the settings for the Log. It has Auttogrowth enabled and restricted growth to the default etting of incredibly large. So what went wrong?Did the transaction log not reuse the available space that was ready for reuse because it was allowed to keep growing to a very very large size? Would it help if I restricted it to 40GB forcing it to reuse the space?Did I need to explicitly BEGIN and COMMIT transactions for each statement.Your help gratefully appreciated this is not the first time this has happened to me and I would really like to be able to manage transaction log files to a reasonable size when in Simple Recovery ModeOur next attempt will be to use transactions around the MERGE statements and a smaller log max size.ThanksE:w00t:

trigger to restrict access for changing login permissions in sql server 2008

Posted: 27 Aug 2013 02:51 AM PDT

Hi Friends,Let us assume I have 2 logins XXX & YYY. XXX-->sysadminYYY-->all databases reader permission.XXX is trying to change the permission for YYY login to sysadmin or db_owner for all databases. Is there a way to restrict the access instead of removing the sysadmin privilege for XXX login.Thanks in advance..

sp_getrecords to get all records from a table

Posted: 27 Aug 2013 05:17 PM PDT

Hi, I have tried and created one sp which will get the table name as input and will return all the records in that table. I will map this sp in the SSMS keyboard shortcut (just like Alt + F1 to return the table structure) so that i can use this shortcut to get the records from that table instead of writing some thing like SELECT * FROM tablename. this sp works fine and helped me a lot. however, if the table is belong to a schema then we have to pass the table name along with schema like schema.tablename. In this case, the sp is failing. If i put single quotes between the table name like 'schema.tablename' it is working fine. But is there any option to tweak the sp so that we dont have to pass the table name in quotes.The sp iscreate PROC [dbo].[sp_getrecords] ( @TableName varchar(4000) ) AS exec('select * from '+@TableName+'')

Scripting CMS

Posted: 27 Aug 2013 02:19 AM PDT

I've looked but perhaps my GoogleFu isn't good enough. Is there a way to script a CMS server group and script servers into it?Regards,Erin

Query Save Help

Posted: 27 Aug 2013 02:04 AM PDT

Hi Guys, I google but couldn't any find help. Here is the issue. From SSMS if I want to save any sql to .sql from File==>Save SqlQuery.Sql==>ask destination where I am gonna save and at last hit OK. It should save my Query in .SQL, right? for some reason its saving my query as .txt. Is anyone can help me why he doing this or which option do I have to change. Thank You....

[SQL Server 2008 issues] Delete Vs Truncate difference on rollback

[SQL Server 2008 issues] Delete Vs Truncate difference on rollback


Delete Vs Truncate difference on rollback

Posted: 26 Aug 2013 11:06 PM PDT

I guess anyone who has read even basic SQL will be aware of this classy question. And most of the people have fell for the catch on the difference based on rolling back the transaction."Delete can be rolled back but Truncate cannot"Some time back i cleared it by experimenting that Truncate can also be rolled back, IF, it is contained inside the Transaction scope AND session is not closed. However my question is if the session is closed and we have full recovery model, then can we roll back the truncate from log ? I guess yes if the pages allocated for deletion by the truncate process are not yet overwritten by any other process (?). Please clarify.

Calculating AVG in mdx for reporting services 2008

Posted: 27 Aug 2013 06:19 PM PDT

Hello , I am new to MDX and would like to know how to calculate average in MDX . I tried several expressions but i failed .I have a ITSM cube . I would like to calculate average of incidents per month and for a group .Number of incident = [Measures].[Nombre incidents]Per month = [Date création].[Mois]Organised by the group = [Groupe affecté - Historique].[Groupe affecté].&[N1-Hotline] I am using SSRS . Thanks .Regards .My actual MDX is (without average calculation) :SELECT NON EMPTY { [Measures].[Nombre incidents] } ON COLUMNS, NON EMPTY { ([Date création].[Mois].[Mois].ALLMEMBERS ) } DIMENSION PROPERTIES MEMBER_CAPTION, MEMBER_UNIQUE_NAME ON ROWS FROM ( SELECT ( { [Date création].[Année].&[2012] } ) ON COLUMNS FROM ( SELECT ( { [Groupe affecté - Historique].[Groupe affecté].&[N1-Hotline] } ) ON COLUMNS FROM [Incidents])) WHERE ( [Groupe affecté - Historique].[Groupe affecté].&[N1-Hotline], [Date création].[Année].&[2012] ) CELL PROPERTIES VALUE, BACK_COLOR, FORE_COLOR, FORMATTED_VALUE, FORMAT_STRING, FONT_NAME, FONT_SIZE, FONT_FLAGSThanks ...

SQL Server Services in the 2008 SQL Configuration Manager FAILED

Posted: 27 Aug 2013 08:30 AM PDT

I was told in my book to check to status of the SQL Server Services and to start it if its stopped. Well, when i click on SQL Server Services, it says: "The remote procedure call failed."I'm checking windows update to see if there is an update i need to install. I do have SS2012 on my computer as well. Everything seems to be running fine on it. I don't know if there might be some conflicting issues though.HEre were the books instructions:[quote]Start the SQL Configuration Manager utility in the Configuration Tools folder, located in the Microsoft SQL Server 2008 program group. In the left pane, click SQL Server Services. In the right pane, examine the status of the SQL Server (SQLEXPRESS) service. If the status is Stopped, right-click the service, and then click Start. Wait for the status to change to Running, and then close SQL Configuration Manager.[/quote]When i right click there is no start or stop and refreshing it means no difference. Any advice?

Update even if there is not a match

Posted: 27 Aug 2013 01:13 PM PDT

Hi ProfessionalsI am running an update to update the columns and tag the licensable column as either, Licensable, Non Licensable or Unknownproblem is when there is not a match it does nothing, is there a way to also update the licensable column to unknown if there is no match[code]UPDATE dbsource SET softwaremanufacturer = dbref.Amended_SW_Manufacturer, productname = dbref.Amended_Product_name, productversion = dbref.Amended_Product_Version, licensable = dbref.category FROM dbo.newtable dbsourceINNER JOIN ( SELECT Raw_SW_Manufacturer,Amended_SW_Manufacturer, Raw_Product_Version,Amended_Product_Version, Raw_Product_Name,Amended_Product_Name,category FROM datalookuptable GROUP BY Raw_SW_Manufacturer,Amended_SW_Manufacturer, Raw_Product_Version,Amended_Product_Version, Raw_Product_Name,Amended_Product_Name,category) dbref ON dbref.Raw_SW_Manufacturer = dbsource.softwaremanufacturer and dbref.Raw_Product_Version = dbsource.productversion and dbref.Raw_Product_Name = dbsource.productname[/code]

What is @Dummy ?

Posted: 16 May 2013 12:49 AM PDT

Hello all! I've been assigned to deconstruct and document a rather large Stored Procedure (SQL 2008). This procedure simply declared about a dozen of other procedures with I will need to anaylize and document. I'm coming into an environment where a handleful of other developers wrote, programmed, and left and not a damn thing was documented. So, I along with the help of someone else, are decontructing it all and documenting it. Anyway, the SP starts off like this:ALTER PROCEDURE [dbo].[The Name of this very SP](@Dummy varchar(20))asExec [SP #1] 1Exec [SP #2] 1...and so on.I have two questions. 1) What does [i]@Dummy [/i]do?2) What do the "1" indicate after firing off each SP?Thanks in advance for your help!!

DATALENGTH much faster than LEN in where clause with varchar(max)

Posted: 27 Aug 2013 10:26 AM PDT

hy,I read a lot of previous post, but I could not find why the running time is so different,making some changes to the "where" conditionI need to delete some record from a table with an exact match.here an exampleCREATE TABLE TO_DROP_BIG_HTML( [BIG_HTML] [varchar](max) NULL) ON [PRIMARY]select count(*), avg(DATALENGTH(BIG_HTML)) from TO_DROP_BIG_HTML-- 5000, 16215here the t-sql with duration estimation declare @start_time datetime select @start_time = getdate()-- ORIGINAL QUERYdelete TO_DROP_BIG_HTML where BIG_HTML = 'NOREC' select DATEDIFF(ms, @start_time, getdate()) -- 1366 select @start_time = getdate()-- adding LEN()delete TO_DROP_BIG_HTMLwhere LEN(BIG_HTML) < 20and BIG_HTML = 'NOREC' select DATEDIFF(ms, @start_time, getdate()) -- 43 select @start_time = getdate()-- replacing with DATALENGTH()delete TO_DROP_BIG_HTMLwhere DATALENGTH(BIG_HTML) < 20and BIG_HTML = 'NOREC' select DATEDIFF(ms, @start_time, getdate()) -- 26every query in the Exection plan does a Table Scan cost 70-79%I can understand that adding more condition in the where I improve performance, but I don't understand the big difference between DATALENGTH and LENRemarks that the original table has 180k record and 5 gb data:43 vs 26 ms become huge more than 10 min vs 12 sec can you explain me why?thank youL

Unable to open Step output file

Posted: 27 Aug 2013 05:19 AM PDT

Hi I am running sql script inside job.But sql is not saving the results in the file which i specified('Unable to open Step output file').I tried same thing on different server, it works fine.Both are are 2008 R2.Is there any server level setting that i have to look at.On both servers i logged in as sa.Any ideas why is it working on server1 ,but not on server2?Tnx advance

Replication without primary keys

Posted: 27 Aug 2013 07:30 AM PDT

Hi,My tables do not have primary keys and as I understand it, transactional replication requires primary keys so my question is: Has anybody found a 3rd party solution to implement Replication when your tables do not have primary keys? We have over 3,000 tables and it would not be possible to alter them to add primary keys so I was just wondering is there another way to implement this.Thanks in advance, :-DIsabelle

Using a parameter to select dates from an Oracle Database

Posted: 27 Aug 2013 08:06 AM PDT

I have a table with two fields: Fromdate and todate that I change every month to the current month value.For example this month fromdate is '2013-08-01' and todate is '2013-08-31' Then when I run the program from a job, it will alread have the date range in the selection process. This is what I do in Teradata which works: DECLARE @tempfromdate AS varchar(10)DECLARE @fromdate AS varchar(10)DECLARE @temptodate AS varchar(10)DECLARE @todate AS varchar(10) select @tempfromdate = fromdate, @temptodate = todate from tbl_fiscperset @fromdate = CONVERT(VARCHAR(10), @tempfromdate, 111)set @todate = CONVERT(VARCHAR(10), @temptodate, 111)DECLARE @SQL VARCHAR(MAX) SET @SQL = ' SELECT *FROM OPENQUERY (TERADATA,''select * from teradata tablewhere reportdate between between ''''' + @fromdate + ''''' and ''''' + @todate + ''''''')'EXEC (@SQL)***EDIT***sorry, I should have added this to the post.This is what works in Oracle with a hard coded dates:where to_char(RPT_DATE,''''yyyy-mm-dd'''') between ''''2013-01-01'''' and ''''2013-08-31''''I can't get the parameter to work.Any thoughts?Thanks

Reporting services

Posted: 27 Aug 2013 02:53 AM PDT

So we have some reports (which I didnt develop) that work fine if I run them on the server reporting services is configured on, but if they are ran from my machine, or from any other box, they fail with the error Cannot create a connection to data source If I go into the reports using this data source, and click on the history tab it says - Credentials used to run this report are not storedThe data source is currenly using windows integrated security. Is the only way to get around this error to use "credentials stored securely in the reportserver" and specify an account to use?

Finding Smart Hierarachical order based on interdependencies

Posted: 27 Aug 2013 07:38 AM PDT

I have a table with two columns, DealID & NetOutDeals (consider this as foreign key to DealID). I am trying to find the Order in which I can execute my deals. [code="sql"]--Create TableCREATE TABLE [DealExecutionOrder]( [DealID] [int] , [NetOutDeals] [varchar](30)) ON [PRIMARY]--Inserting Sample DataINSERT INTO [DealExecutionOrder]VALUES (1, '3,10,12'), (2, '3,5,7'), (3, '0'), (4, '6'), (5, '3'), (6, '0'), (7, '0'), (10,'0'), (12,'5')[/code]Here are the business rules: 1. value 0 in NetOutDeals means no DealID dependencies. I can straight away execute DealID with 0 value in NetOutDeals first. 2. From here, I can execute a deal only if all deals in the corresponding NetOutDeals are executed. For eg: DealID 1 can be executed only after 3, 10, 12 (again 12 can be executed only after 5 (again 5 can be executed only after 3)). I need to come up with the hierarchical order of DealID to process my deals. Order does not matter at same level. Eg: 3, 6, 7, 10 can come in any order but should be before next immediate deals that depend only on this list. So output DealID order should be like this: (6,10,7,3), (5, 4), (2, 12), (1)Order does not matter within the brackets. Can someone help me to achieve this?

Difference of two consecutive datetime rows

Posted: 20 Aug 2013 02:39 AM PDT

HI,I have the following tableEntryID DateInserted InsertedBy1776285 2013-06-03 07:46:38.340 5921776286 2013-06-03 07:47:47.677 5921776287 2013-06-03 07:48:17.367 5921776288 2013-06-03 07:49:08.750 5921776289 2013-06-03 07:49:08.750 5921776290 2013-06-03 07:49:45.177 5921776291 2013-06-03 07:54:54.290 5921776292 2013-06-03 07:57:11.703 5921776293 2013-06-03 07:57:35.930 831776294 2013-06-03 07:58:33.843 831776295 2013-06-03 07:58:36.293 5921776296 2013-06-03 07:58:54.853 831776297 2013-06-03 07:59:06.523 5921776298 2013-06-03 07:59:27.633 831776299 2013-06-03 07:59:46.383 831776300 2013-06-03 08:00:02.020 5921776301 2013-06-03 08:00:04.390 831776302 2013-06-03 08:00:29.590 5921776303 2013-06-03 08:01:00.240 5921776304 2013-06-03 08:01:12.943 831776305 2013-06-03 08:01:31.150 831776306 2013-06-03 08:01:31.990 5921776307 2013-06-03 08:01:50.373 831776308 2013-06-03 08:02:10.840 831776309 2013-06-03 08:02:30.243 831776310 2013-06-03 08:03:03.737 831776311 2013-06-03 08:04:08.750 5921776312 2013-06-03 08:04:14.723 831776313 2013-06-03 08:04:27.033 5921776314 2013-06-03 08:05:26.617 831776315 2013-06-03 08:05:26.617 831776316 2013-06-03 08:05:38.527 83Now I want to get the difference between 2 consecutive dateinserted col in hours or mins into another column say Time diff grouped by on the inserted by col since i want total time taken by each person inserted.like as belowEntryID DateInserted InsertedBy TimeDiff1776285 2013-06-03 07:46:38.340 592 diff(2013-06-03 07:47:47.677-2013-06-03 07:46:38.340)-- should be the output of this col either in mins or hours.Also if the difference is > than 3 mins I want only 3 mins as the output.1776286 2013-06-03 07:47:47.677 5921776287 2013-06-03 07:48:17.367 5921776288 2013-06-03 07:49:08.750 5921776289 2013-06-03 07:49:08.750 5921776290 2013-06-03 07:49:45.177 5921776291 2013-06-03 07:54:54.290 5921776292 2013-06-03 07:57:11.703 5921776293 2013-06-03 07:57:35.930 831776294 2013-06-03 07:58:33.843 831776295 2013-06-03 07:58:36.293 5921776296 2013-06-03 07:58:54.853 831776297 2013-06-03 07:59:06.523 5921776298 2013-06-03 07:59:27.633 831776299 2013-06-03 07:59:46.383 831776300 2013-06-03 08:00:02.020 5921776301 2013-06-03 08:00:04.390 831776302 2013-06-03 08:00:29.590 5921776303 2013-06-03 08:01:00.240 5921776304 2013-06-03 08:01:12.943 831776305 2013-06-03 08:01:31.150 831776306 2013-06-03 08:01:31.990 5921776307 2013-06-03 08:01:50.373 831776308 2013-06-03 08:02:10.840 831776309 2013-06-03 08:02:30.243 831776310 2013-06-03 08:03:03.737 831776311 2013-06-03 08:04:08.750 5921776312 2013-06-03 08:04:14.723 831776313 2013-06-03 08:04:27.033 5921776314 2013-06-03 08:05:26.617 831776315 2013-06-03 08:05:26.617 831776316 2013-06-03 08:05:38.527 83Thanks in advance.

index dmv stats

Posted: 27 Aug 2013 02:28 AM PDT

HiI have an alert set up for 'Number of unused indexes' set to a number above a certain threshold.Our servers get rebooted every month therefore flushing out the stats from the dmv's that I use to trigger these alerts.I suppose this is a 'how long is a piece of string' question, but is 1 months worth of stats going to give me a decent idea of my index usage - i don't feel that it is but i welcome peoples opionions....

will not using the statement terminator ';' break code in future?

Posted: 26 Aug 2013 07:21 PM PDT

i've been searching for some definitive (or as definitive as it can be, since we dont all work for Microsoft) about whether SQL that doesn't have the ';' terminator will break at the point they decide to make it mandatory.[url]http://www.sqlservercentral.com/Forums/Topic1261877-392-1.aspx[/url][url]http://www.linkedin.com/groups/Future-deprecated-feature-Must-terminate-72017.S.198380247[/url]this next link mentions 'Not ending Transact-SQL statements with a semicolon' is not supported in a future version[url]http://technet.microsoft.com/en-us/library/ms143729.aspx?goback=%2Egmr_4764645#![/url]i'm sure it wont but i'd prefer to know ;)

Fastest way to read a 600MB table (in memory)

Posted: 27 Aug 2013 04:32 AM PDT

A few days ago I came across this interesting problem:I cannot get more than 15-19mb/s is there any limitation that I need to know about?The query is a simple select (not doing sorting) and the database is read-only : "select * from tablename"Tried local and remote and still get the same throughput therefore is not a network problem.Launching multiple queries in parallel bring the total time down almost linearly as I increase the number of parallel connections (which bring different sections of the data).Finally the table fits entirely in memory therefore no DiskIO is involved either.If someone has any insight, please chime in.

Maintenance Plan Job Proxy Failures

Posted: 27 Aug 2013 03:30 AM PDT

I have a problem that has been kicking my butt for a couple of days and I just can't find how to fix it.Server:SQL Server 2008 R2 Std Ed 10.50.2500 SP1Windows Server 2008 R2 StdError:MessageExecuted as user: MyServer\_sqlagentservice. Microsoft (R) SQL Server Execute Package Utility Version 10.50.2500.0 for 64-bit Copyright (C) Microsoft Corporation 2010. All rights reserved. Started: 8:45:51 AM Could not load package "Maintenance Plans\MaintenancePlan-Backups" because of error 0xC0014062. Description: The LoadFromSQLServer method has encountered OLE DB error code 0x80040E4D (Login failed for user 'MyServer\_sqlagentservice'.). The SQL statement that was issued has failed. Setup:1. Created maintenance plan to run backups.2. Created a Credential assigning the identity to the local user account that runs the SQL Server Agent service (MyServer\_sqlagentservice)3. Created proxy "JobAgentProxy" using the above credential4. In the maintenance plan job, I set the step Run As to "JobAgentProxy".When I run this job, it fails. I have other servers (all 2005) that use this proxy setup with no problem what-so-ever!Any help here would be greatly appreciated.:Greg

NEWID()

Posted: 26 Aug 2013 07:54 PM PDT

Hi All,I have to know which algorithm is used in NEWID() function or to know how it works internally?Regards,Ningaraju N E

OMR into SQL Server Reports.

Posted: 27 Aug 2013 02:06 AM PDT

Does any one know how to include OMR (Optimum Mark Recognition) into sql server reports?Thanks in advance

Sum

Posted: 26 Aug 2013 10:22 PM PDT

HI,I have table like the given belowgrade losal hisal1 700 12002 1201 14003 1401 20004 2001 30005 3001 9999so, i need the Total of that cols like given below grade losal hisal1 700 12002 1201 14003 1401 20004 2001 30005 3001 9999Total 8304 17599plz help me

calculaing percentage Increase or Decrease

Posted: 26 Aug 2013 07:28 PM PDT

Hi,I need help for calculaing percentage Increase or Decrease in Price of some Product for last two years.I have some table gg_Price_TDate Product Price1-01-2013 Bingo 50.07 2-01-2013 Tingo 52.07 3-01-2013 Zingo 56.07 . . .. . .27-08-2013 Sigo 59.07It is having different price for each day and I want to know with what percentage this price differs every year, If we take it for last two years 2012 and 2011

Data Sync between two Applications on different Database servers and sync should be done on set up tables data on both sides

Posted: 26 Aug 2013 09:53 PM PDT

Hi Everyone,I am in a situation where two applications are interacting from two DB servers and i need to sync the data of set up tables on both Application sides.Can anyone provide a feasible low cost approach.Thanks in advance.:-)

Duplicates

Posted: 26 Aug 2013 11:29 PM PDT

When you have a temp table being populated. Can you join on that table so you don't get duplicates? I tried using distinct but even if the time stamp is off by just a little, it will add it because it is distinct.

SQL Agent Job Scheduling

Posted: 27 Aug 2013 12:19 AM PDT

Let's say we have an instance of SQL Server (the default instance) and two PROD databases within in that default instance, DB1 and DB2. The job scheduler is global to the instance, so will it not work if I have a Index rebuild scheduled (SQL Job) for DB1 at 1:00am and a Index rebuild scheduled for DB2 at 1:00am, those two jobs should not interfere with each other, correct?

DeNormalize Key Value Hierarchy table

Posted: 26 Aug 2013 09:48 PM PDT

Hi All,I have an hierarchy table as below which stores the key data.And the value for this key will be stored in another table.And the Value can be multiple i e Key-Value 1:n.And this values can be associated with an Item.Now I have to De normalize this table so that I can use the same in Query builder search?What is the best solution and design?ID Name Parent ID Category ID 19 Identifier NULL 320 Type of Classification 19 321 Entry 19 322 Title NULL 323 Language NULL 324 Description NULL 325 Keyword NULL 326 Structure NULL 327 Aggregation level NULL 328 Version NULL 429 Status NULL 430 Contribute NULL 431 Role 30 432 Entity 30 433 Date 30 434 Identifier NULL 535 Type of Classification 34 536 Entry 34 537 Contribute NULL 538 Entity 37 539 Date 37 540 Metadata schema NULL 541 Language NULL 5ThanksNingaraju

CTE in MERGE

Posted: 27 Aug 2013 12:01 AM PDT

Can we use CTE in MERGE statement ?If possible then please post a sample code of that...

Tuesday, August 27, 2013

[how to] How to go about modeling the main object of relationship?

[how to] How to go about modeling the main object of relationship?


How to go about modeling the main object of relationship?

Posted: 27 Aug 2013 08:36 PM PDT

I'm using mySQL and myISAM tables.

I a have a bunch of objects that I want to group together (1 object belongs to 1 and only 1 group AND 1 group can have many objects), and I absolutely need to know the main object of the group (1 group can only have 1 required main object).

So far, I've build a model that I believe is the right one.

But I don't know how to go about modeling the main object in the group. What is the perfect solution?

group_object  ----------------  group_object_id (PRIMARY KEY)  name    object  ----------------  object_id (PRIMARY KEY)  group_object_id (FOREIGN KEY)  name  

Use Database to Store Data Extracted From Internet

Posted: 27 Aug 2013 07:50 PM PDT

I'm mining 500 million users, and their "followers" from a social network using their API. The extraction of data itself is not a problem, since I can do it with my scripts. However having 500 million users and their followers in a list in memory can be very costly.

My script created two lists,one with the users that I already got their followers, and one with the users to be looked at (I would get each user, put their followers in the queue, write to file, and then go to the next one.) So it would be 2 long lists that I cannot handle in memory. So I thought of a database.

So finally to my question, is it better for me to use a relational database, or a NoSQL, graph, database, like Neo4j. The only information I'm getting now is the user ID and the ID of the followers, which later I want to analyse (for graph theory research.) I thought of a database because I might try add more information later as well.

Thank you.

Mysql performance issue when selecting text column

Posted: 27 Aug 2013 07:35 PM PDT

I have a performance problem when selecting rows containing text fields:

SELECT id FROM message  WHERE NOT(message.sender_id = 368352 AND message.is_deleted_sender = 1)      AND NOT(message.recipient_id = 368352 AND message.is_deleted_recipient = 1)      AND recipient_id = 368352  AND is_spam = 0 AND is_deleted_recipient = 0  ORDER BY   timestamp desc  LIMIT 0, 5;  

5 rows in set (0.07 sec)

SELECT message FROM message  WHERE NOT(message.sender_id = 368352 AND message.is_deleted_sender = 1)      AND NOT(message.recipient_id = 368352 AND message.is_deleted_recipient = 1)      AND recipient_id = 368352  AND is_spam = 0 AND is_deleted_recipient = 0  ORDER BY   timestamp desc  LIMIT 0, 5;  

5 rows in set (0.15 sec)

Explain is the same for both queries:

mysql> EXPLAIN SELECT id FROM message WHERE NOT(message.sender_id = 368352 AND message.is_deleted_sender = 1) AND NOT(message.recipient_id = 368352 AND message.is_deleted_recipient = 1)  AND recipient_id = 368352  AND is_spam = 0 AND is_deleted_recipient = 0 ORDER BY   timestamp desc  LIMIT 0, 5;  +----+-------------+---------+------+---------------------------------------+--------------+---------+-------------------+------+-----------------------------+  | id | select_type | table   | type | possible_keys                         | key          | key_len | ref               | rows | Extra                       |  +----+-------------+---------+------+---------------------------------------+--------------+---------+-------------------+------+-----------------------------+  |  1 | SIMPLE      | message | ref  | sender_id,recipient_id,recipient_id_2 | recipient_id | 6       | const,const,const |   86 | Using where; Using filesort |  +----+-------------+---------+------+---------------------------------------+--------------+---------+-------------------+------+-----------------------------+  

Indexes (I know there's maybe no need for recipient_id index when there's recipient_id_2, but that's what I have there):

mysql> show indexes from message;  +---------+------------+----------------+--------------+----------------------+-----------+-------------+----------+--------+------+------------+---------+  | Table   | Non_unique | Key_name       | Seq_in_index | Column_name          | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment |  +---------+------------+----------------+--------------+----------------------+-----------+-------------+----------+--------+------+------------+---------+  | message |          0 | PRIMARY        |            1 | id                   | A         |    14693109 |     NULL | NULL   |      | BTREE      |         |  | message |          1 | thread_id      |            1 | thread_id            | A         |     4897703 |     NULL | NULL   |      | BTREE      |         |  | message |          1 | sender_id      |            1 | sender_id            | A         |      253329 |     NULL | NULL   |      | BTREE      |         |  | message |          1 | sender_id      |            2 | is_spam              | A         |      267147 |     NULL | NULL   |      | BTREE      |         |  | message |          1 | sender_id      |            3 | is_deleted_sender    | A         |      333934 |     NULL | NULL   |      | BTREE      |         |  | message |          1 | recipient_id   |            1 | recipient_id         | A         |      272094 |     NULL | NULL   |      | BTREE      |         |  | message |          1 | recipient_id   |            2 | is_spam              | A         |      277228 |     NULL | NULL   |      | BTREE      |         |  | message |          1 | recipient_id   |            3 | is_deleted_recipient | A         |      445245 |     NULL | NULL   |      | BTREE      |         |  | message |          1 | timestamp      |            1 | timestamp            | A         |    14693109 |     NULL | NULL   |      | BTREE      |         |  | message |          1 | recipient_id_2 |            1 | recipient_id         | A         |      206945 |     NULL | NULL   |      | BTREE      |         |  | message |          1 | recipient_id_2 |            2 | is_deleted_sender    | A         |      277228 |     NULL | NULL   |      | BTREE      |         |  | message |          1 | recipient_id_2 |            3 | is_spam              | A         |      277228 |     NULL | NULL   |      | BTREE      |         |  | message |          1 | recipient_id_2 |            4 | is_chat              | A         |      341700 |     NULL | NULL   |      | BTREE      |         |  +---------+------------+----------------+--------------+----------------------+-----------+-------------+----------+--------+------+------------+---------+  

How do I deal with that? I can even do something like

SELECT message.message FROM message,      (SELECT id FROM message        WHERE NOT(message.sender_id = 368352 AND message.is_deleted_sender = 1)           AND NOT(message.recipient_id = 368352 AND message.is_deleted_recipient = 1)                    AND recipient_id = 368352  AND is_spam = 0 AND is_deleted_recipient = 0             ORDER BY   timestamp desc  LIMIT 0, 5) m   WHERE m.id = message.id;  

and it runs faster: 5 rows in set (0.06 sec)

My guess is it has something to do with filesort - larger data is sorted slower or something. I copied that database from production to another server to experiment with but strangely enough it runs fast in both cases.

Efficiently query MAX over multiple ranges

Posted: 27 Aug 2013 07:53 PM PDT

When performing a MIN() or MAX() over a single range covered by an appropriately sorted index, SQL Server does a TOP() and so returns the value after fetching just one row. When the search criteria include more than one range, SQL Server instead grabs all the indexed values from both of the ranges and does a stream aggregate, which is far slower than performing a TOP() for each sub-value.

For example, assume a large number of orders per customer in a table like:

CREATE TABLE orders  (    customer_id int,    quantity int  )  

Running this query:

SELECT MAX(quantity)   FROM orders  WHERE customer_id IN (1,2)  

will result in a query that takes several times as long as if only one customer ID were specified.

What is the most efficient way to perform a query like the above? Relatedly, if separate results were needed (i.e. GROUP BY customer_id), what would the best method be?

SQL Fiddle: http://sqlfiddle.com/#!3/ef0c6/1

What is the best way to manage user access to MySQL via PHP?

Posted: 27 Aug 2013 02:29 PM PDT

I am working on a web application that requires auditing db queries in MySQL. In every application that I have developed or worked on it is standard practice to store the DB credentials in a protected configuration file and access the DB through that one user. Auditing, then, must be managed by the code (I'm using PHP).

My question: would it be better to create user accounts for each user in MySQL and use these credentials to create the DB connection? Doing so would allow MySQL to log the queries by each user either through the general query log or Mcafee's mysql-audit plugin.

I have read some older posts that claim allowing multiple user accounts creates security vulnerabilities, but I have not read a clear explanation of how/why.

It may be worth noting: admins create user accounts and set user permissions. Users cannot self-register.

Thanks for any help you can provide.

ORA-21780: Maximum number of object durations exceeded

Posted: 27 Aug 2013 02:00 PM PDT

I am getting this error when records are streamed over to another database

Oracle DB version:11.2.0.3.0

Transaction Flow: DML on Schema1@DB1 Streamed to Schema2@DB2 then trigger on this table will insert into Schema3@DB2 then trigger on this table will insert into table in Schema4@DB2

ORA-21780 error happening at the last stage.

Please advise.

Thanks, Sreedhar.

Enabling JMX For Hadoop HDFS & Also MapReduce

Posted: 27 Aug 2013 12:03 PM PDT

I'm having a hard time figuring out how to enable JMX to submit metrics for HDFS and MapReduce jobs in Hadoop (CDH4).

I've seen several links and read through 'The Definitive Guide' and 'Hadoop Operations' on the 'monitoring' chapters and it goes through a great background on Metrics1, Metrics2, JMX JSON files, and that the latter is the preferred method, but I can't find out how to enable it for HDFS and MapReduce independently.

This blog has a good intro but it doesn't monitor Task and Data Nodes. I'm not sure how to enable it for everything. Does anyone have any steps? Thanks!

Dynamic file name for file import

Posted: 27 Aug 2013 12:12 PM PDT

I'm trying to figure out a way that I can pass a filename into a stored procedure that can import a file. However, after setting up the SQL dynamically, the object can't be found.

DECLARE @fileName varchar(200),       @sql varchar(max)    SET @fileName = 'C:\file.csv';    SET @sql = 'SELECT *      INTO #import      FROM OPENROWSET(BULK ''' + @fileName + ''',      FORMATFILE=''C:\format.xml'',      FIRSTROW = 2) AS a';    EXEC(@sql);    SELECT * INTO #stage  FROM #import;  

The result

(27823 row(s) affected)  Msg 208, Level 16, State 0, Line 29  Invalid object name '#tmtImport'.  

Does SQL Server support restoring to a point in time down to the millisecond?

Posted: 27 Aug 2013 11:13 AM PDT

Using the Management Studio GUI, I am only able to restore a database to a point in time down to the second. Is this just a limitation of the GUI or if I use a script will it restore to the millisecond I specify?

I'm trying to do it with a script and it 'seems' like it's ignoring the millisecond but unfortunately the date value I'm comparing to is, unfortunately, not necessarily the exact time the record was written so I just want to rule out any possibility that the problem could be because of a limitation of SQL Server.

Improve performance with the WHERE NOT IN sub-select clause

Posted: 27 Aug 2013 01:59 PM PDT

In the following query, I have to count transactions for each customer. [EDIT]However, I have to exclude from the result set entirely, customers that have a transaction older than one year.

Shouldn't the query optimizer be smart enough to only evaluate existence once for each customer?

--Count transactions on customers that are less than 1 year old      SELECT t1.CUSTID,COUNT(*)    FROM CUST_TRX t1    WHERE NOT EXISTS (       SELECT FIRST 1 1       FROM CUST_TRX t2       WHERE         t2.CUSTID=t1.CUSTID AND        t2.DATED<CURRENT_DATE-365      GROUP BY t2.CUSTID    )    GROUP BY t1.CUSTID  

There are no naturals in my query plan. This query is performing as if the database is running the existence clause for every transaction instead of running it for every customer. Performance is the same if I remove the GROUP BY in the sub-query.

Is there a better way to do this so that I may get better performance out of the database? Hopefully a simple select query will work avoiding a CTE if possible (that would introduce other challenges). Due to other group by criteria (not shown here) I'm not able to simply check MIN(DATED), I really need to perform another query.

Getting the employee history of Sales department from HR database in Oracle

Posted: 27 Aug 2013 11:22 AM PDT

I am currently using the 'hr' database with Oracle 10g. You can view the schema diagram over here: http://docs.oracle.com/cd/B13789_01/server.101/b10771/diagrams001.htm#sthref63

What I would like is to retrieve the history of all employees who have worked in the 'Sales' department. I have selected only first name, last name, and job title for the working example but I'm getting the same job title where I should be getting two different ones.

This is the query I have so far:

SELECT a.first_name, a.last_name, b.job_title  FROM employees a, jobs b, job_history c, departments d  WHERE d.department_id = (SELECT department_id FROM departments WHERE department_name = 'Sales')  AND c.employee_id = a.employee_id  AND a.job_id = b.job_id  AND c.department_id = d.department_id;  

Any help would be appreciated. JazakAllah khayr.

MySQL: mysqld_safe options

Posted: 27 Aug 2013 09:06 PM PDT

Is there a way to specify these options in configuration file?

I've tried to add them into [mysqld_safe] section but it doesn't work:

[mysqld_safe]  numa-interleave = 1  flush-caches = 1  

-

# ps -ww -lfC mysqld_safe  F S UID        PID  PPID  C PRI  NI ADDR SZ WCHAN  STIME TTY          TIME CMD  4 S root     17180     1  0  80   0 - 26549 wait   15:06 pts/1    00:00:00 /bin/sh /usr/bin/mysqld_safe --datadir=/var/lib/mysql --pid-file=/var/lib/mysql/mysql.pid  

Please note that I'm using Percona server.

How force specific table to not logging (for all DML)?

Posted: 27 Aug 2013 07:20 PM PDT

We using Oracle 9i . I'm still learn about admin Oracle (I'm DBA but other vendor).

We implement manually at our databases a trigger over LOGON and LOGOFF to save some information about our users sessions.

We execute an insert at LOGON and an update at LOGOFF over our table. This table was created as NOLOGGING.

Our problem is the amount of archive generated by day, growth a lot. After check with log miner I detect is the updates over this table the reason.

I research little and found the information the NOLOGGING work only for very specific situations and all UPDATEs still logging.

I don't need keep safe this table or backup it. We extract the information all days... if I loose some days I can live with it. But I can't keep this overhead .

Is there no way to force a table to not logging for all DMLs in Oracle?
Any alternative solution? (where I keep the triggers and my own table)

Regards
Cesar

How to setup SSL in MSSQL Server 2012 with own certificate?

Posted: 27 Aug 2013 01:26 PM PDT

Environment:

Windows 7 Professional x64 in a domain, running MS SQL Server 2012. I have lokal Admin rights, so messing up the system is easy. My SQL Server 'names' are 'SQLEXPRESS' and 'MSSQLSERVER'. FQDN should be for example 'my-pc.mydomain.local'.

Problem:

I dont know the right way to setup SSL on this MS SQL Server. I actually only want to setup SSL with a certificate created of my own. Can anybody help me out here? Most of the documentation online only describes the way of going through a CA and have different knowleadge as a prerequirement.

What are the circumstances where autovacuum can be disabled?

Posted: 27 Aug 2013 01:03 PM PDT

I have a table where I am performing only inserts, never deletes/updates. I notice sometimes that autovacuum runs on this table, even though this is the case.

autovacuum: VACUUM ANALYZE public.twitter_shares (to prevent wraparound)    

It is taking a long time, and it is having an impact on the performance of my DB. Is it safe for me to just disable autovacuum for this table? Since I am not performing deletes/updates, I don't understand why autovacuum is even needed, and why postgres decides to run it.

SQL Server 2008 - How to check FK integrity?

Posted: 27 Aug 2013 03:28 PM PDT

I'd like to pull a partial dataset from production for test environments - e.g. Copy the production database with only the first 100 rows of each table or 5% of the data - which ever comes first. Simple enough. For each table, just... SELECT TOP 100 * INTO DESTINATION FROM SOURCE"

The problem is maintaining data integrity for FK. Is there a native SQL Server SP/FX to verify the integrity of each row's FK after the data has been copied over?

If not, once the production schema is copied to sandbox environments, I was planning to implement the following logic:

PSUEDO:

For each source table{   While (Destination Tbl =<100 rows/5% of Source Tbl COUNT(*)) {     If FK exists on source tbl{       For each FK, query referenced FK tbl and insert results into FK's corresponding destination tbl     }    Insert row from source tbl to destination tbl   }  }  

I don't want to recreate the wheel or make it harder than it needs to be. If you see any holes in my logic, please let me know. Thanks in advance.

How to keep the structure of the Tablix when there is no data to show

Posted: 27 Aug 2013 02:19 PM PDT

We have a SSRS report which shows the result of a dataset in a tablix. If the query in the dataset returns no data, the header of the Tablix gets displayed but not the tablix cells below the header. I know there is a property to NoRowMessage, but in fact it is not what we want. Because when I specify a message, SSRS shows the message instead of the empty tablix.I must show the tablix structure as it is, but with empty cells.

I even set the rule for each cell value of the tablix using IsNothing function, to show blank (""), if the value is null, but it didn't help.

Do you have any idea? Thanks for your help in advance.

What's a good way to model user authorization to hierarchical data?

Posted: 27 Aug 2013 08:16 PM PDT

I'm wanting to implement something that's basically an ACL in SQL Server (2008, we'll be moving to 2012). We're working with farm production information. We will have users who need to be authorized to view production records, but only at certain vertical levels in a hierarchy.

Our data hierarchy looks like this:

System  - Farm    - Group      - Animal  

The idea is that some users will have access at the System level, and can see records for all Farms, Groups, and Animals within that System. Likewise, some users will have permission starting at the Farm level, and need access only linked to that Farm and all Groups (and animals) within it.

Each table contains a primary key column, and a foreign key column linking it to the parent record (along with whatever other attributes each entity requires).

What I've implemented in the past is two-table system for linking users to the appropriate items they're allowed to see. Implemented here, it would look like this:

Table:  Authorizations          Table:  FullAuthorizations  Columns:    Id (PK)             Columns:    Id (PK)              UserId                          UserId              ObjectId                        SystemId              ObjectType                      FarmId                                              GroupId                                              AnimalId  

The application inserts a record into Authorizations, with the user to authorize, the record id (System id, Farm id, etc), and the type of record (System, Farm, etc). The FullAuthorizations table is used to denormalize the farm hierarchy for easier/faster filtering of data. A trigger is used on the Authorizations table (and each of the farm, etc, tables) to update FullAuthorizations. I considered using a View here, in a previous project with additional levels of entities, and the performance was quite poor once we began getting several hundred thousand records.

The queries would look something like:

SELECT *  FROM dbo.Animals a  WHERE EXISTS (      SELECT 1      FROM dbo.FullAuthorizations fa      WHERE fa.UserId = 1 AND fa.AnimalId = a.Id  )  

In the other project where we're doing this, the solution is performant, but feels like a bit of a hack, and I especially don't like that we can't maintain referential integrity on Authorizations with the associated objects. I'd appreciate feedback on some other possible solutions. I've been looking at things like Nested Sets, but not sure something like that fits this particular problem.

Oracle shared memory exception ORA-04031

Posted: 27 Aug 2013 02:16 PM PDT

I'm trying to establish an Oracle database connection. It throws the following exception:

ORA-04031: unable to allocate 4048 bytes of shared memory     ("shared pool","unknown object","sga heap(1,0)","kglsim heap")  

I have tried connecting the database through JDBC as well as SQL Developer, however it throws the exception in both case.

How can I fix this?

How can extract the table schema from just the .frm file?

Posted: 27 Aug 2013 08:08 PM PDT

I have extracted the data directory of mysql from a backup and need to get the schema from an old table, however it's a backup from a different machine.

I have read a fair number of tutorials today on how to do this, but each time it seems to fail or I end up having to reinstall mysql because mysql hangs or crashes. (Create a different database, create table with same name, replace file, stop/start engine, recover from frm. Tried in varying orders and combinations.)

Is there any external tool that can extract the schema from the .frm file? I can see the column names if I open up the file. I had a look but I can't seem to find anything that will enable me to do this.

Thanks in advance.

Memcached plugin on MariaDB?

Posted: 27 Aug 2013 03:16 PM PDT

I'd like to try new NoSQL feature in MySQL 5.6 but I am using MariaDB 10.0.2 on Debian 6 and don't fancy coming back to MySQL.

I'm wondering whether the memcached plugin has been added to MariaDB? And if not whether one can still use it as an addon?

And if not, can I use the existing Cassandra plugin of MariaDB to the same effect?

How to embed a sub-prodecure call in a SELECT statement in an Oracle 11g PL/SQL stored procedure

Posted: 27 Aug 2013 04:16 PM PDT

I need to figure out a way to embed an Oracle PL/SQL sub-procedure call in a SELECT statement, within another procedure in the same package.

I am using SQLDeveloper 3.0 with an Oracle 11g database.

I have already developed a stored procedure 'acctg_detail_proc()' that generates a detailed list of accounting transactions within a specified period. What I am trying to do is create a summary report procedure 'acctg_summary_proc()' using the detailed data returned by acctg_detail_proc().

Since I am new to PL/SQL, all I have learned so far is how to retrieve the detailed data via a ref cursor, then LOOP through it, FETCHing each individual detail row. I want to figure out how acctg_summary_proc() can substitute that call to acctg_detail_proc() for a table name in a SELECT statement with a GROUP-BY clause. Here is the source code for an anonymous block where I tried to test it:

SET SERVEROUTPUT ON;  DECLARE      start_date VARCHAR2(50) := '04/01/2012';      end_date VARCHAR2(50) := '04/30/2012';      c_acctg_refcur    SYS_REFCURSOR;  BEGIN    acctg_rpt_pkg.acctg_detail_proc(start_date, end_date, c_acctg_refcur);    SELECT       date_posted,      debit_acct,      credit_acct,      SUM(dollar_amt)    FROM c_acctg_refcur    GROUP BY      date_posted,      debit_acct,      credit_acct;    CLOSE c_acctg_refcur;  END;  

When I try to execute this code, I get the following error:

PL/SQL: ORA-00942: table or view does not exist

I realize I could use a nested SELECT statement instead of a table name, but I want to avoid duplication of source code. Is there any way to 'alias' a ref cursor so I can reference its data in a SELECT statement?

Here is some further background info: The called sub-procedure has ~600 lines of code, and selects 40 columns of data from a de-normalized VIEW. The corporate DBAs will not let me create any VIEWs that contain WHERE clauses, so that is not an option for me.

Thanks in advance, Ken L.

Repairing Broken Binary Replication in PostgreSQL 9.0

Posted: 27 Aug 2013 01:16 PM PDT

I have a binary replication that was stopped for so long that the WALs were removed and as a result, it ended up being old. I'm trying to reestablish the replication and the best way I've found so far is following the steps on the PostgreSQL wiki:

  • Issue select pg_start_backup('clone',true); on master
  • rsync everything except for pg_xlog from master to slave
  • Issue select pg_stop_backup(); on master
  • rsync pg_xlog

But the database is too big (300 GB), my connection is not really amazing (like 800 kB/s) and the files in base keep changing. So I was wondering if there's a more optimal way to do this.

Failed copy job deletes all users

Posted: 27 Aug 2013 06:16 PM PDT

Since the progression of this was apparently somewhat difficult to follow the first time around:

I attempted a completely boring, been-done-a-thousand-times-before copy of a database using the copy database wizard with the detach/reattach method.

The copy failed. The log indicates that it was unable to execute a CREATE VIEW action for a particular view, because the datasource for the view did not exist. This is interesting in its own right, as the source most certainly exists, and the view(s) in question are fully functional in the source database. I'm not really clear, just yet, on how significant this is, as I've yet to figure out precisely why this generated an error.

This resulted in the deletion of all non-system user associations from the source database, leaving me with users dbo, information_schema, sys, and guest. Non-system roles were also deleted. Schemas were unaffected.

I have since restored the damaged database from backup. Academically, however, I would like to know the following:

  1. Why would a failed copy operation strip the user associations from the source database?
  2. Is there any sort of maintenance/rebuild/repair operation that could be performed on the source database to repair it?
  3. The loss of the users was immediately obvious, but given the rather mysterious nature of a failed copy job apparently damaging the source database, how concerned should I be about less obvious effects? In theory, I would expect restoring from backup would alleviate this concern, but do I have any cause to worry about, e.g., the master database?

This is entirely repeatable. I've made a handful of copies (manually) for the sake of experimenting with this particular issue, and in each case, the failed copy job obliterates the users and roles from the source database.

Removing the views that generated errors allows the copy to complete, and, as one would expect, produces a copy with identical data, users, etc., in addition to leaving the source database unaltered.

If it's important, I've tried rebuilding the indexes of the system databases, as well as the damaged database, to no appreciable effect.

The error generated:

1:00:25 PM,5/28/2013 1:00:25 PM,0,0x,ERROR : errorCode=-1073548784 description=Executing the query "CREATE VIEW [Sourcing].[PermittedArrProducts]  AS  SELECT     dbo.tblArrProducts.ArrProductID, dbo.tblArrProducts.ArrangementID, dbo.tblArrProducts.ContainerTypeID, dbo.tblArrProducts.Quantity  FROM         Sourcing.PermittedArrangements INNER JOIN                        dbo.tblArrProducts ON Sourcing.PermittedArrangements.ArrangementID = dbo.tblArrProducts.ArrangementID    " failed with the following error: "Invalid object name 'Sourcing.PermittedArrangements'.". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.  

SQL Server 2005 Replication

Posted: 27 Aug 2013 09:16 PM PDT

I am in the process of creating Replication between 2 Remote Servers, server 1 is the Distributor and Publisher and server 2 is the Subscription.

server 1 windows 2003 server 192.168.10.1 connected by vpn SQL Server 2005 domain1.local

server 1  windows 2003 server  192.168.10.1 connected by vpn  SQL Server 2005  domain1.local  

server 2 windows 2003 server 192.168.10.6 connected by vpn SQL Server 2005 domain2.local

server 2  windows 2003 server  192.168.10.6 connected by vpn  SQL Server 2005  domain2.local  

When I setup up Replication everything looked fine until I looked at the sync status and it said:

The Agent could not be started    An exception occurred while executing a transact-sql statement or batch    sqlserveragent error request to run job  server1-username blah blah blah  

From user sa refused because the job is already running from a request by user sa changed database context to technical error 22022.

I have cleared jobs in the server agent as well as restarted the service.

Could this be something to do with authentication between two non trusted domains as I can browse and even control each sql server via SQL studio but just not setup replication?

Yes I can manage each SQL Server in SSMS and we are using merge with snapshot.

Multiple parents and multiple children in product categories

Posted: 27 Aug 2013 12:16 PM PDT

I am making a ecommerce site. In this site I want to categorise the items into three different layers

primary category             sub category           sub category    >>electronic             >>smart phone          samsung    cameras                       tablets              nokia                                    laptop               apple                                  headphone  

In the above table, I want to display the sub category after the customer selects the primary one. At the same time the 'samsung' also comes under 'camera'. Like this a parent can have any number of children and one child can have many parents. In the future we may change the primary and secondary.

What is the best solution for this? Which model will adopt our category: tree or nested?

Mysqldump tables excluding some fields

Posted: 27 Aug 2013 07:16 PM PDT

Is there a way to mysqldump a table without some fields?

Let me explain:
I have a MySQL database called tests. In tests I have 3 tables: USER, TOTO and TATA. I just want to mysqldump some fields of table USER, so excluding some fields like mail, ip_login, etc.

How can I do this?

Sybase SQL Anywhere 12 - Get all indexes which are unique -> ambigious sysindexes error

Posted: 27 Aug 2013 11:16 AM PDT

we are using a Sybase SQL Anywhere 12 db.

In the db there are indices, which are unique, but shouldn't be unique.

Therefore I search for a quick way to list all tables with unique primary keys.

I tried

SELECT z.name FROM sysobjects z JOIN sysindexes ON (z.id = i.id) WHERE type = 'U'  

The result was an error message: Anweisung konnte nicht ausgeführt werden. Tabellenname 'sysindexes' ist mehrdeutig SQLCODE=-852, ODBC 3-Status="42S13" Zeile 1, Spalte 1

Roughly translated: sysindex is ambiguous.

I found on internet the query:

select 'Table name' = object_name(id),'column_name' = index_col(object_name(id),indid,1),  'index_description' = convert(varchar(210), case when (status & 16)<>0 then 'clustered' else 'nonclustered' end  + case when (status & 1)<>0 then ', '+'ignore duplicate keys' else '' end  + case when (status & 2)<>0 then ', '+'unique' else '' end  + case when (status & 4)<>0 then ', '+'ignore duplicate rows' else '' end  + case when (status & 64)<>0 then ', '+'statistics' else case when (status & 32)<>0 then ', '+'hypothetical' else '' end end  + case when (status & 2048)<>0 then ', '+'primary key' else '' end  + case when (status & 4096)<>0 then ', '+'unique key' else '' end  + case when (status & 8388608)<>0 then ', '+'auto create' else '' end  + case when (status & 16777216)<>0 then ', '+'stats no recompute' else '' end),  'index_name' = name  from sysindexes where (status & 64) = 0  order by id  

Which looked what i wanted. But there was still the same result of ambigious sysindexes.

What dows ambigious indexes mean in this context? Will/Can this cause any error in future?

As workaround I used sybase central (which by the way opens always on first monitor, not on the one where it was closed - ugly behaviour), and found that a item indices showed what i searched for.

But I still want to know how a programmatically solution looks like.

Mongo connection failing with 'Transport endpoint is not connected'

Posted: 27 Aug 2013 05:16 PM PDT

I have a 2 server installation.

A web server with Apache and a DB server with MongoDB.

I am load testing it, and on ~300 RPS I am getting this error:

PHP Fatal error: Uncaught exception 'MongoConnectionException' with message 'Transport endpoint is not connected'.

The only thing I am noticing is that right before the fail, I am getting a lots of connections on Mongo:

insert  query update delete getmore command flushes mapped  vsize    res faults locked % idx miss %     qr|qw   ar|aw  netIn netOut  conn       time        0    659      0      0       0       1       0   208m  1.28g    40m      0        0          0       0|0     0|0    62k   217k   486   03:57:20   

Almost 500 connections here... but never more than that!

Mongo is 2.0.3. PHP is 5.3.x (latest of Debian install...)

Help!

Search This Blog