Friday, August 23, 2013

[SQL Server 2008 issues] Mdmp files

[SQL Server 2008 issues] Mdmp files


Mdmp files

Posted: 22 Aug 2013 05:52 PM PDT

Hi All,In my production server , SQL Error log file size is growing by creating mdmp (memory dum files in c drive ).How i can stop them.

SSAS Filter field not working

Posted: 22 Aug 2013 01:59 PM PDT

In the attached image you can see the Cube structure, Item Dimension, Hierarchies used in Item Dim,attribute relationship defined in Item dim+ the data in browser.We can see that while browsing data and applying filter at the filter field we are not getting the appropriate result.Note :Amt Cat : Amt at the Item Category level (using calculated measure shown below)iif(isempty([Measures].[AMT])=true, null,([Measures].[AMT],ancestor([Item].[Items].CurrentMember,[Item].[Items].[Item Category])))Amt Grp : Amt at Item Group level (using calculated measure shown below)iif(isempty([Measures].[AMT])=true, null,([Measures].[AMT],ancestor([Item].[Items].CurrentMember,[Item].[Items].[Item Group])))But by applying the filter at filter expression we get the required result and even by modifying the attribute relationship as shown above we get the appropriate result.Can anyone explain why is this happening so ?

Failover 10,000 databases?

Posted: 22 Aug 2013 04:09 AM PDT

Hi All,It may sound like a clustering question but it's also service restart one.We have a Windows 2008 cluster with one instance of SQL Server 2008R2. There are 10,000+ databases on it. While user_db access is fast, cluster failover takes almost an hour, even with high performing hardware. We would like to drop the failover time. 1/3 of the databases are not active. Almost all of them are on SIMPLE recovery mode.I am considering;- Setting AUTO_CLOSE ON for inactive databases, or OFFLINE- Playing with recovery intervalAnything else you might suggest?Cheers,Kuzey

Backup to another network server

Posted: 16 Aug 2013 02:54 PM PDT

Hi,I am trying to backup from my sql 2005 DB which is on windows server 2003 to sql 2008R2 on windows server 2008R2 but getting access denied,I have tried using SSMS, T-Sql but still getting issue with this.I have created backup folder on my 2008R2 server and assign the full access to Everyone on security permission, I have added user and also grant the FUll Permission.1) I tried using SSMS ut didn't work2) I tried using T-sql, didn't workI have just install the sql 2008R2 on Windows 2008 R2.

query returning to many rows

Posted: 22 Aug 2013 09:08 AM PDT

Hi AllI am confused in trying to find all licensable and non licensable products that match my datalookuptable but it seems to be returning to many rowsMy queries are as follows[code]select count(*) from dbo.newtablereturns 629019 rows************************************************** select n.*,d.categoryfrom newtable n,datalookuptable dwhere n.softwaremanufacturer = d.amended_sw_manufacturer and n.productname = d.amended_product_name and n.productversion = d.amended_product_version and d.category in ('Licensable','Non Licensable') order by d.categoryreturns almost 3 million rows[/code]am i missing something

Performance issue

Posted: 21 Aug 2013 10:54 PM PDT

Hi All,I am migrating 35 million data to another new table(EVALUATION_CRITERIA) using simple joins, But it is taking to execute around 24 hrs and system ram=16 GB,Below are the [b]insert query and attached Execution plan[/b][b]Can any one suggest , is there any best ways can i get Any Time difference If run same code in SSIS Package ?[/b]Records count in user tablesEVALUATION_DETAIL 33240682EVALUATION 1297899EVALFORM 338EVALFORM_CRITERIA 8619EVALFORM_CRITERIA_DETAIL 34630 --ScriptDeclare @EvaluationId Int, @EvalformId IntDeclare CursorData Cursor ForSelect Evaluation_Id, Evalform_Id From EvaluationOpen CursorDataFetch Next From CursorData Into @EvaluationId, @EvalformIdWhile @@Fetch_Status = 0Begin Insert EVALUATION_CRITERIA (EVALUATION_ID, EVALFORM_CRITERIA_ID, TITLE_NAME, BASE_CRITERIA_ID, EVALFORM_CRITERIA_DETAIL_ID, CHILD_EXIST, PRIORITY_ORDER, WEIGHTAGE, ANSWER_TYPE, STATUS, CREATE_BY, CREATE_DATE, LEVEL, SCORE) select e.EVALUATION_ID, efcd.EVALFORM_CRITERIA_ID, efc.TITLE_NAME, efc.BASE_CRITERIA_ID, efcd.EVALFORM_CRITERIA_DETAIL_ID, efc.CHILD_EXIST, efc.PRIORITY_ORDER, efc.WEIGHTAGE, NULL, --efc.ANSWER_TYPE,-- 'A', 1, GETDATE(), efc.LEVEL, efcd.SCORE 'A', 1, GETDATE(), efc.LEVEL, (select MAX(score) from EVALFORM_CRITERIA_DETAIL where EVALFORM_CRITERIA_ID = efcd.EVALFORM_CRITERIA_ID and STATUS = 'A' and OMIT_FROM_SCORE = 'N') score from EVALFORM ef inner join EVALFORM_CRITERIA efc on ef.EVALFORM_ID = efc.EVALFORM_ID left join EVALFORM_CRITERIA_DETAIL efcd on efc.EVALFORM_CRITERIA_ID = efcd.EVALFORM_CRITERIA_ID left join EVALUATION_DETAIL ed on efcd.EVALFORM_CRITERIA_DETAIL_ID = ed.EVALFORM_CRITERIA_DETAIL_ID left join EVALUATION e on ed.EVALUATION_ID = e.EVALUATION_ID where e.EVALUATION_ID=@EvaluationId and efc.STATUS = 'A' Union select @EvaluationId, efc.EVALFORM_CRITERIA_ID, efc.TITLE_NAME, efc.BASE_CRITERIA_ID, 0, efc.CHILD_EXIST, efc.PRIORITY_ORDER, efc.WEIGHTAGE, NULL, --efc.ANSWER_TYPE, 'A', 1, GETDATE(), efc.LEVEL, NULL --efcd.SCORE from EVALFORM ef inner join EVALFORM_CRITERIA efc on ef.EVALFORM_ID = efc.EVALFORM_ID left join EVALFORM_CRITERIA_DETAIL efcd on efc.EVALFORM_CRITERIA_ID = efcd.EVALFORM_CRITERIA_ID where efc.CHILD_EXIST = 'Y' and efc.STATUS = 'A' and ef.EVALFORM_ID = @EvalformId-- Select @EvaluationId, @EvalformIdFetch Next From CursorData Into @EvaluationId, @EvalformId EndClose CursorDataDeallocate CursorData[b]--Attached Execution plan[/b]

User redirection in DB Mirroring

Posted: 22 Aug 2013 04:53 PM PDT

I have configured DB Mirroring with automatic fail over.My users are connected to Server_A .My Partner is Server_B and witness is Server_C.As we know that whenever a fail over occurs Server_B will take the roll from Server_A and it becomes Online.But my point is how the users are redirected to Server_B.Is it the DBA who changes the connection string or the Application Developer or the Database Developer.How ? What happens behind the screen.Please explain this with details..

query to find total number of total number of reads for a stored procedure

Posted: 22 Aug 2013 03:06 AM PDT

Is there a query to find total number of logical reads/physical reads done when a given stored procedure is executed?

backing up msdb after changes

Posted: 22 Aug 2013 09:13 AM PDT

I have found some of my databases that have high vlf counts.It looks like the ones that had the high count have had either small increment growth settings or the setting was set to grow as a percentage.I have now adjusted the Log files to the correct size after following Kimberly Trips advice http://www.sqlskills.com/blogs/kimberly/transaction-log-vlfs-too-many-or-too-few/My question is do i now need to back up the msdb databases on the servers i made the changes too, as our servers get rebooted every month, to keep the new growth settings intact ?

SSRS, cascade parameters, how to make it work for multiple choice (WHERE in ...)

Posted: 22 Aug 2013 06:14 AM PDT

Hi,I created cascade params for my report, it works fine for single selection, but when I check let say 2 params, (AAA, BBB) it doesn't work.So it's only for MULTI VALUES IN PARENT CASCADE PARAM, child is OKMy dataset query:[code="other"]select subCategory from t1where t1.Category in @Category --works OK with = for single selection or @Category = 'All'--errorAn expression of non-boolean type specified in a context where a condition is expected, near ','[/code]in SSRS/Query Designer / Define QUery Parameters window:Parameter Value = AAA ===> runs fines,returns 100 rowsParameter Value = AAA,BBB ===> nothingParameter Value = (AAA,BBB) ===> nothing, etc.. and again: WHERE t1.Category in (@Category) ...Even MSN aknowledge this problem and tricky way to solve it, very bizarre!!! Is there anything else I have to add/change? I googled and found this on http://social.msdn.microsoft.com/Forums/sqlserver/en-US/1b42af8a-d84b-4224-891e-53043b7a0614/how-to-pass-multiple-values-to-a-parameter-while-cascading... =split(Join(Parameters!XXX.value,","),",")But where to put this vbs?TxM

Performance IO issue

Posted: 21 Aug 2013 11:10 PM PDT

Hi All,We have Performance issue on of our Pord server 2005,where we are seeing I/O issues.While montring i could a high I/O values for the Database.Database i/o counter name location value ISOstall[ms]/read request xxxx(database) 25I think the database is causing performance is issue.can any one help me how to troubleshoot this issue ......what is cause for high I/o issue.Thanks.....in advance..

AD Query failed to work last night.

Posted: 22 Aug 2013 08:58 AM PDT

Hello all, I have a query to AD that worked 2 days ago, but did not work last night.SELECT sn, givenname, sAMAccountName, mail, displayNameFROM openquery(ADSI,' SELECT givenName, sn, employeeID, mail, sAMAccountName, displayName FROM ''LDAP://OU=DedicatedRemoteSites,DC=berkshire,DC=loc'' WHERE objectCategory = ''Person'' and objectClass = ''user'' and mail = ''*.org'' and givenName = ''*''');The message I get is this:Msg 7330, Level 16, State 2, Line 1Cannot fetch a row from OLE DB provider "ADSDSOObject" for linked server "ADSI".The only thing that I am aware of that did change is that we had to change our main Administrator Password.Is there something related to this that I need to update somewhere?Thank you in advance for your help.

VMing Instances

Posted: 22 Aug 2013 05:18 AM PDT

Hey folks.. here part of the situation. We're going to P2V some sql servers. I'd like to find the average cpu core usage and the minimum memory requirements for server/database so I know what each VM will require at a bare minimum to continue efficient operations. I realize that with our current configurations SQL Server sucks up the memory allocated to it but if I've allocated 8 gigs and it grabs all that memory, how much of it does it really use on a consistent basis? Does it need 8 gigs? Can it make do with 1? 2? Does it require more than two cores? Does it even need more than one core if it's a low usage system?Anyone have any scripts that can give me this kind of information?Thanks,Erin

Shorten query by using Top predicate

Posted: 22 Aug 2013 01:30 AM PDT

I have situations when I only want to know if I have one record, or more than one record. For instance, a query like this:[code="sql"]SELECT Top 2 AkcesAutoID FROM Podrobnosti Group By AkcesAutoID[/code]I would like to stop as soon as it sees that it has a second record. But when I look at the query plan, the first step, an Index Scan passes (in this case) 85 rows, from an estimated 32,376 rows to the Stream Aggregate function, which then passes only two to the Top function, which then passes only two to the Select function. This is a simple query, but real ones will be considerably more complex, with multiple joins and conditionals.The gist is that I want to know whether all the records matching my criteria have the same value in a particular field, in this case AkcesAutoID. If they are all the same, I can deal with the result set in a particular (simplified) way. If there are more, I don't (at this point) care how many more, I already know that the app has to do something a different way.Reading on the subject indicates that the Top predicate is always applied only to the result set. Is there any way to tell the query engine that I want it to stop working on the problem AS SOON AS it has the second record that meets my criteria, instead of gathering them all and then discarding all but two?

SSIS package error in SQL 2008 ActiveX Script but the sql agent job succeeds

Posted: 22 Aug 2013 04:27 AM PDT

Hi, I am getting this wierd scenario where SSIS SQL agent job suceeds but it actually isnt. I am getting the below error in the job history, but the job suceeds.Code: 0xC00291B1 Source: Parse XML File ActiveX Script Task Description: User script threw an exception: "Error Code: 0Error Source= Microsoft OLE DB Provider for SQL ServerError Description: Query timeout expiredError on Line 282".End ErrorDTExec: The package execution returned DTSER_SUCCESS (0).Package execution validated as success.Please share your thoughts, Thank you for spending your time.

Maintenance Solution

Posted: 22 Aug 2013 01:41 AM PDT

I came across a SQL file from Netbut did not get the information of what it do..Its a Maintenance solution.sqlPlease tell me what can i be helped with this file..I think it would of grt help.. please guide me to use it

Script to retrive Configuration files from servers 2000 to 2012

Posted: 21 Aug 2013 08:31 PM PDT

HI Everyone,can any one have idea to script that retrives configuration files from all servers.Inputs are most welcome.Cheers

Results viewer cannot execute the query error

Posted: 22 Aug 2013 12:27 AM PDT

Hello, We need to copy paste data from excel into a SQL table from time to time. We have no control over the table, it is generated and given to us periodically. We are getting an error now: "The results viewer cannot execute a query with more than 655 columns in the project list". I know that the answer is, normalize the table and reduce the number of columns. Unfortunately, we have no control over the table. So is there any easy way to get data into the table under this achitecture? Not sure I want to build SSIS for this, but might I have too? I am hoping there is a workaround someone out there might be able to hand off to me. Thanks in advance!

Possible to restrict the types of file stored in a Filestream container?

Posted: 22 Aug 2013 12:47 AM PDT

In the near future, I may be responsible for implementing a DB back-end for an application which stores documents, videos, images, and other such BLOB data. Potentially, this will be done in Filestream. My question is, is it possible to restrict the types / sizes of files on the SQL side, or would such logic have to be implemented at the application?From some quick Googleing, it looks like it would need to be on the app side of the fence, but I'd like to confirm...Thanks,Jason

Log shipping errror

Posted: 21 Aug 2013 09:52 PM PDT

Hi everyone.Hope someone can offer some guidance here.Set up log shipping. All looked ok. The noticed that I was getting the [SQLSTATE 42000] (Error 14421). The step failed. Error on the secondardy server in regards to the LSAlert job.when I run select * from msdb.dbo.log_shipping_monitor_secondaryI do intend see the last_restored_file as blank for the database.However I do see the log shipped from Primary and does exist on secondary.The copy and restore jobs say everything is ok , but as I can see from the above query it is not being restored onto the secondary Database.When looking at the restore job on the secondatry server I see these messages :2013-08-22 11:45:27.57 Skipped log backup file. Secondary DBAnything I can do to check \ resolve this ?Is the quickest way to resolve it , is to reconfigure the LS for this DB again ?many thanks all.

Replication: add a new table with out a new snapshot

Posted: 07 Aug 2013 09:40 PM PDT

Hello,i've got a database with 500 GB DATA and 200 GB INDEX. I had to add an article (table) to the replication. I want do avoid, that the replication creates a new snapshot. We need about 7 hours to create the new index in the database.Is it possible, to add article without a new snapshot. I read something, that only the difference ( in my example: 1 table) is stored in the snapshot.Publisher: SQL 2008 R2 SP2 / OS Windows Enterprise 2008 48 GB RAMSubscriber: SQL 2008 R2 SP2 / OS Windows Standards 2008 48 GB RAMDistribution-Server: SQL 2012 / OS Windows Enterprise 24 GB RAMcreate the snapshot needed about 30 Minutesdeliver the snapshot needed about 6,5 Hourscreate index neede about 7 HoursThanks for you help,Andreas

Deadlock issues

Posted: 21 Aug 2013 11:16 PM PDT

Getting Deadlock issues on regular basis..where Select insert or select update is involved in SPCan UPDLOCK & HOLDLOCK solve the issue in select query??or else suggest something you have comeacross

Google Analytics SQL Import

Posted: 08 May 2012 09:07 PM PDT

Hi AllI was just wondering if anyone has ever done a Google Analytics import to SQL via SSIS?A quick google brought up some C# scripts, a PHP web scraper and using the java client to export to CSV and then import it, but was wondering if anyone has managed to query the API and load it direct in SSIS to the DB?This was a task which was done a couple of years ago and I have been asked to re-ignite the flame to get it moving again and the previous way was to use xp_cmdshell to execute a file which loads it to CSV and imports it, which I have no trouble with, just wondering if anyone has a better solution.Thanks

How to Create configuration files for installation of SQL Server

Posted: 21 Aug 2013 07:30 PM PDT

Hi,I am Looking for procedure that create a configuration file for installation of sql server and how it works. can any one help me out?. Thanks. Replays are most welcome.Cheers

XSD to Table

Posted: 21 Aug 2013 07:39 PM PDT

Hi All,Is there any T SQL script which converts XSD to table schema?

Thursday, August 22, 2013

[SQL Server] How To Load Multiple XML Files

[SQL Server] How To Load Multiple XML Files


How To Load Multiple XML Files

Posted: 21 Aug 2013 06:13 PM PDT

Hi All, I'm required to load multiple XML Files from one folder into a database table, I also need to check that the file starts with "Filename"e.g Departments_1 I need to make sure the the file starts with "department" as there'll be other files in the folder e.g Departments_2at the moment I am able to load one file at a time using the script below that checks if a file exists before loading, is it possible to achieve this using T-Sql? any help would be appreciated.Here's part of the script that I'm using to load the data into a temp table below:--Load all XML data firstDECLARE @isExists INT--Cost Centresexec master.dbo.xp_fileexist 'C:\inetpub\wwwroot\Prof1t\FTP\<CLIENT_FOLDER>\Departments_1.xml', @isExists OUTPUTIF @isExists = 1BEGIN print 'Departments.xml exists'INSERT INTO tmpCostCentreXML (CostCentreCode, CostCentreName)SELECT Y.CostCentres.query('CostCentreCode').value('.', 'VARCHAR(30)'),Y.CostCentres.query('DepartmentName').value('.', 'VARCHAR(60)')FROM (SELECT CAST(x AS XML)FROM OPENROWSET( BULK 'C:\inetpub\wwwroot\Prof1t\FTP\<CLIENT_FOLDER>\Departments_1.xml', SINGLE_BLOB) AS T(x)) AS T(x)CROSS APPLY x.nodes('Departments/Department') as Y(CostCentres); print 'Loaded Cost Centre XML'ENDELSEBEGINprint 'Departments_1.XML doesn''t exist'ENDHere's the XML example:<?xml version="1.0" encoding="UTF-8"?>-<Departments> -<Department> <DepartmentName>MAGNUM POC</DepartmentName> <CostCentreCode>30</CostCentreCode> </Department> </Departments>Thanks Teee

Deteremine who deleted a view

Posted: 22 Aug 2013 04:54 AM PDT

Hello all,Is there a way to determine who deleted a view?Thanks

[how to] Install and Configure Oracle 11g using c# program

[how to] Install and Configure Oracle 11g using c# program


Install and Configure Oracle 11g using c# program

Posted: 22 Aug 2013 08:10 PM PDT

I need to create a windows application program using c# which will allow me to install oracle client 11g and also configure ODBC automatically with just one click, as my customers have limitations in technology and hence the installation and configuration is very difficult.

Is it possible and also if you could help with some code reference?

How to relate two rows in the same table

Posted: 22 Aug 2013 06:11 PM PDT

I have a table where the rows can be related to each other, and logically, the relationship goes both ways (basically, is directionless) between the two rows. (And if you're wondering, yes, this really should be one table. It is two things of the exact same logical entity/type.) I can think of a couple ways to represent this:

  1. Store the relationship and its reverse
  2. Store the relationship one way, constrain the database from storing it the other way, and have two indexes with opposite orders for the FKs (one index being the PK index)
  3. Store the relationship one way with two indexes and allow the second to be inserted anyway (sounds kind of yucky, but hey, completeness)

What are some major pros and cons of these ways, and of course, is there some way I haven't thought of?

Here's a SQLFiddle to play with: http://sqlfiddle.com/#!12/7ee1a/1/0. (Happens to be PostgreSQL since that's what I'm using, but I don't think this question is very specific to PostgreSQL.) It currently stores both the relationship and its reverse just as an example.

How to structure IF condition in MySQL trigger?

Posted: 22 Aug 2013 07:23 PM PDT

I am trying to write a MySQL trigger. I have two tables like this:

Table A------------------------------Table B

order_id------sku-----------------order_id------order_#-------sku_copy

568---------AAA---------------568---------2345  567---------BBB---------------567---------6789-------empty column  566---------CCC---------------566---------1234  

When a customer makes a purchase a new record is added to each table. I have added column 'sku_copy' to Table B, so it does not get populated when a new record is created.

When a new record is created, I want my trigger to copy the 'sku' field in Table A to the 'sku_copy' field in Table B. However, the problem I am having is how to structure the following condition in the trigger.

IF: 'order_id' in Table A matches 'order_id' in Table B. THEN: copy 'sku' from that Table A record to the record in Table B with the matching 'order_id'. The data should be added to Table B 'sku_copy'.

I am using the following SQL trigger but it gives this error when it's run:

"#1363 - There is no OLD row in on INSERT trigger"

Here is the trigger:

DELIMITER $$  CREATE TRIGGER trigger_name      AFTER INSERT ON tableA      FOR EACH ROW BEGIN        INSERT INTO tableB      SET sku_copy = OLD.sku,           order_id = OLD.order_id,          order = OLD.order;  END $$  DELIMITER ;  

Can some one show me how to correct the error in this code or suggest a better one?

Thank you for any help you can give.

Here is an update:

I tried this trigger (this is the live data instead of simplified as in the above examples) but get an error code:

"#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE virtuemart_order_id=new.virtuemart_order_id; END IF; END' at line 7"

Here is that trigger:

DELIMITER $$  CREATE TRIGGER `sku_after_update` AFTER UPDATE ON `uau3h_virtuemart_order_items`     FOR EACH ROW    BEGIN      IF (old.order_item_sku_copy != new.order_item_sku)      THEN      UPDATE uau3h_virtuemart_orders          SET order_item_sku_copy=new.order_item_sku,                            WHERE virtuemart_order_id=new.virtuemart_order_id;      END IF;    END$$  DELIMITER ;  

Does anyone have any suggestions on how to make this trigger work?

Reverse connect by prior level value for arbitrarily-deep hierarchy

Posted: 22 Aug 2013 01:57 PM PDT

Background

Using a menu hierarchy to drive a login process for users. Users have the ability to set their preferred menu item. When they log in, if they have a preferred menu item set, the system directs them to that item. If no preferred menu item is set, they log into the default menu item for their "most important" role.

Code

The query uses connect by prior to get the list of menus:

  SELECT      LEVEL AS menu_level,      jmi.name AS menu_name,      jmi.id AS menu_id    FROM      jhs_menu_items jmi, (        SELECT          jmi.id        FROM          jhs_users ju        JOIN jhs_user_role_grants jurg ON          ju.id = jurg.usr_id        LEFT OUTER JOIN user_menu_preferences ump ON          ju.id = ump.jhs_usr_id        LEFT OUTER JOIN default_menu_preferences dmp ON          jurg.rle_id = dmp.jhs_rle_id        JOIN jhs_menu_items jmi ON          -- Retrieve the user's preferred menu item, failing to the default          -- if no preference is set.          jmi.id = coalesce(            ump.jhs_menu_items_id,            dmp.jhs_menu_items_id          )        WHERE          ju.username = 'USERNAME' AND          ROWNUM = 1        ORDER BY          dmp.role_priority_sort      ) menu_preference      -- Derive the menu hierarchy starting at the user's preference, going back to     -- the root menu item.    START WITH jmi.id = menu_preference.id    CONNECT BY PRIOR jmi.mim_id = jmi.id  

Problem

A root menu item has NULL for its parent (mim_id). The user's menu preference is a menu item leaf node, which can be found at any level in the hierarchy (the maximum depth is 3, in this case).

When the data is returned, the values for the LEVEL pseudocolumn (alias MENU_LEVEL) are in reverse order:

╔════════════╦═══════════╦══════════════╗  ║ MENU_LEVEL ║ MENU_NAME ║ MENU_ITEM_ID ║  ╠════════════╬═══════════╬══════════════╣  ║          1 ║ MenuTab3  ║ 100436       ║  ║          2 ║ MenuTab2  ║ 101322       ║  ║          3 ║ MenuTab1  ║ 101115       ║  ╚════════════╩═══════════╩══════════════╝  

This should actually return:

╔════════════╦═══════════╦══════════════╗  ║ MENU_LEVEL ║ MENU_NAME ║ MENU_ITEM_ID ║  ╠════════════╬═══════════╬══════════════╣  ║          3 ║ MenuTab3  ║ 100436       ║  ║          2 ║ MenuTab2  ║ 101322       ║  ║          1 ║ MenuTab1  ║ 101115       ║  ╚════════════╩═══════════╩══════════════╝  

However, since the hierarchy is connected by starting from the user's preferred menu item, and worked back up to the root menu item, it makes sense that LEVEL is counting "backwards".

Having the level reversed means we can ask, "What is the 3rd-level menu item for the user named 'USERNAME'"? Expressed in as a SQL where clause:

WHERE menu_level = 3 AND username = 'USERNAME';  

Question

How would you reverse the value of LEVEL for an arbitrarily-deep hierarchy?

For example, something like:

SELECT    LEVEL AS MENU_LEVEL_UNUSED,    max(LEVEL) - LEVEL + 1 AS MENU_LEVEL  FROM ...  

Obviously that won't work because max is an aggregate function.

Ideas

  • We could add a column to jhs_menu_items that stores the depth. This is a bit redundant, though, because the hierarchy itself contains that information.
  • We could wrap the jhs_menu_items table in a view that calculates the depth. This could get computationally expensive.
  • Is this a good candidate for WITH?

Migrating from MSSQL to MySQL using MySQL Workbench tool

Posted: 22 Aug 2013 12:31 PM PDT

I'm trying to migrate few tables from MSSQL to MySQL using MySQL Workbench migration wizard. All work fine for structure migrations but when I go to the data migration section it throws an error for one table:

ERROR: dbo.Documents:SQLExecDirect(SELECT [DocumentID], [CategoryID], CAST([DocumentName] as NVARCHAR(255)) as [DocumentName], [Active], [NavigatorID], CAST([DocumentText] as NTEXT) as [DocumentText], [UseSubtitle], CAST([DocumentSubtitle] as NVARCHAR(255)) as [DocumentSubtitle], CAST([DocumentPlainText] as NTEXT) as [DocumentPlainText], [DocumentType], CAST([DocumentLink] as NVARCHAR(255)) as [DocumentLink], [Sitemap], CAST([SubtitleImage] as NVARCHAR(255)) as [SubtitleImage], CAST([MetaTags] as NVARCHAR(8000)) as [MetaTags], CAST([MetaDescription] as NVARCHAR(8000)) as [MetaDescription], [AccessLevel] FROM [ctool_test].[dbo].[Documents]): 42000:1131:[Microsoft][ODBC SQL Server Driver][SQL Server]The size (8000) given to the convert specification 'nvarchar' exceeds the maximum allowed for any data type (4000).

2131:[Microsoft][ODBC SQL Server Driver][SQL Server]The size (8000) given to the convert specification 'nvarchar' exceeds the maximum allowed for any data type (4000).

Based on that what I can understand it limits columns with 'nvarchar' data to max size of 4000 when MySQL can handle 65535.

Any clue how I can get this to work?

Thanks

Oracle 10g and Active Directory not behaving as expeted

Posted: 22 Aug 2013 11:59 AM PDT

I'm trying to connect to our Oracle 10g 64bit database running on a Windows 2003 server authenticating with an Active Directory user.

I found this weird results on our Development environment which I cannot replicate on the testing environment (same setup, different Active Directory)

I created a user as "OPS$DOMAIN\USER" and works ok if I log-in locally from the server, for example, running SQLPLUS / would connect directly without asking for username/password. SHOW USER would return "USER is "OPS$DOMAIN\USER"".

The weird thing happened when I tried to log-in from my computer (win 7 32bit oracle 11 client) logged as domain\user. SQLPLUS /@MYINSTANCE did not work... it wouldn't connect, asking me for a valid user/password.

After several attempts, a colleague suggested creating the user "OPS$USER" without indicating the domain. This does not work when I try and connect locally, but it works when I connect from my machine. So now, SQLPLUS /@MYINSTANCE from my computer works, and SHOW USER returns "USER is "OPS$USER"".

Makes any sense?

Finally, we tried the same on our Testing environment, where it all seems to work as expected (only works if I use "OPS$DOMAIN\USER").

Any ideas why might this be happening? My machine is part of the Development domain environment, before you ask :D

I'm starting to believe this has nothing to do with Oracle config, but maybe some weird setup on our Dev AD.

Thanks in advance!

Allow developers to run database maintenance

Posted: 22 Aug 2013 11:49 AM PDT

We use the database solution by Ola Hallengren. We're trying to give our developers a way to run the maintenance stored procedures after they do an ETL. Our developers have locked down permissions. We've installed Ola's stored procs: CommandExecute, CommandLog, DatabaseIntegrityCheck, and IndexOptimize.

Using Procedure with Execute as login as an example. I then setup the following:

-- Create the stored procedure in master. Otherwise,   -- the certificate will need to be backed and restored  -- to the database where the stored procedure exists  use [master]  go      -- create certificate that the procedure will be signed with  create certificate maintenance_proc_cert      encryption by password = 'H@rdP@w0rd'      with subject = 'Enable maintenance through procedure',      expiry_date = '01/01/2030';  go      -- create login that will be granted right to run maintenance  create login maintenance_login from certificate maintenance_proc_cert;  go      -- grant the login the SA role  exec master..sp_addsrvrolemember @loginame = N'maintenance_login', @rolename = N'sysadmin'  go      -- create procedures  if exists (select * from sys.objects where type = 'P' and name = 'SPECIAL_DatabaseIntegrityCheck')  drop procedure SPECIAL_DatabaseIntegrityCheck;  go  create procedure [dbo].[SPECIAL_DatabaseIntegrityCheck]      @Databases nvarchar(max),      @CheckCommands nvarchar(max) = 'CHECKDB',      @PhysicalOnly nvarchar(max) = 'N',      @NoIndex nvarchar(max) = 'N',      @ExtendedLogicalChecks nvarchar(max) = 'N',      @TabLock nvarchar(max) = 'N',      @FileGroups nvarchar(max) = NULL,      @Objects nvarchar(max) = NULL,      @LockTimeout int = NULL,      @LogToTable nvarchar(max) = 'N',      @Execute nvarchar(max) = 'Y'  as  begin      execute dbo.DatabaseIntegrityCheck          @Databases = @Databases,          @CheckCommands = @CheckCommands,          @PhysicalOnly = @PhysicalOnly,          @NoIndex = @NoIndex,          @ExtendedLogicalChecks = @ExtendedLogicalChecks,          @TabLock = @TabLock,          @FileGroups = @FileGroups,          @Objects = @Objects,          @LockTimeout = @LockTimeout,          @LogToTable = @LogToTable,          @Execute = @Execute;  end  go  if exists (select * from sys.objects where type = 'P' and name = 'SPECIAL_IndexOptimize')  drop procedure SPECIAL_IndexOptimize;  go  create procedure [dbo].[SPECIAL_IndexOptimize]      @Databases nvarchar(max),      @FragmentationLow nvarchar(max) = NULL,      @FragmentationMedium nvarchar(max) = 'INDEX_REORGANIZE,INDEX_REBUILD_ONLINE,INDEX_REBUILD_OFFLINE',      @FragmentationHigh nvarchar(max) = 'INDEX_REBUILD_ONLINE,INDEX_REBUILD_OFFLINE',      @FragmentationLevel1 int = 5,      @FragmentationLevel2 int = 30,      @PageCountLevel int = 1000,      @SortInTempdb nvarchar(max) = 'N',      @MaxDOP int = NULL,      @FillFactor int = NULL,      @PadIndex nvarchar(max) = NULL,      @LOBCompaction nvarchar(max) = 'Y',      @UpdateStatistics nvarchar(max) = NULL,      @OnlyModifiedStatistics nvarchar(max) = 'N',      @StatisticsSample int = NULL,      @StatisticsResample nvarchar(max) = 'N',      @PartitionLevel nvarchar(max) = 'N',      @MSShippedObjects nvarchar(max) = 'N',      @Indexes nvarchar(max) = NULL,      @TimeLimit int = NULL,      @Delay int = NULL,      @LockTimeout int = NULL,      @LogToTable nvarchar(max) = 'N',      @Execute nvarchar(max) = 'Y'  as  begin      execute dbo.IndexOptimize          @Databases = @Databases,          @FragmentationLow = @FragmentationLow,          @FragmentationMedium = @FragmentationMedium,          @FragmentationHigh = @FragmentationHigh,          @FragmentationLevel1 = @FragmentationLevel1,          @FragmentationLevel2 = @FragmentationLevel2,          @PageCountLevel = @PageCountLevel,          @SortInTempdb = @SortInTempdb,          @MaxDOP = @MaxDOP,          @FillFactor = @FillFactor,          @PadIndex = @PadIndex,          @LOBCompaction = @LOBCompaction,          @UpdateStatistics = @UpdateStatistics,          @OnlyModifiedStatistics = @OnlyModifiedStatistics,          @StatisticsSample = @StatisticsSample,          @StatisticsResample = @StatisticsResample,          @PartitionLevel = @PartitionLevel,          @MSShippedObjects = @MSShippedObjects,          @Indexes = @Indexes,          @TimeLimit = @TimeLimit,          @Delay = @Delay,          @LockTimeout = @LockTimeout,          @LogToTable = @LogToTable,          @Execute = @Execute  end  go      -- sign the procedures with the certificate  add signature to SPECIAL_DatabaseIntegrityCheck  by certificate maintenance_proc_cert  with password ='H@rdP@w0rd';  go  add signature to SPECIAL_IndexOptimize  by certificate maintenance_proc_cert  with password ='H@rdP@w0rd';  go      -- Grant execute to the procedure to NNEACC Admins  grant execute on SPECIAL_DatabaseIntegrityCheck to [developer1];  grant execute on SPECIAL_IndexOptimize to [developer1];  go  

Then as developer1, I tried running:

EXECUTE dbo.SPECIAL_DatabaseIntegrityCheck      @Databases = 'ALL_DATABASES',      @CheckCommands = 'CHECKDB',      @LogToTable = 'Y';  

However, it fails with the error:

Msg 50000, Level 16, State 1, Procedure DatabaseIntegrityCheck, Line 156  The stored procedure CommandExecute is missing. Download http://ola.hallengren.com/scripts/CommandExecute.sql.    Msg 50000, Level 16, State 1, Procedure DatabaseIntegrityCheck, Line 170  The table CommandLog is missing. Download http://ola.hallengren.com/scripts/CommandLog.sql.    Date and time: 2013-08-22 14:44:30  

I found that I had to sign each of the procs that the parent proc calls. I did this by running:

add signature to DatabaseIntegrityCheck  by certificate maintenance_proc_cert  with password ='H@rdP@w0rd';  go  add signature to IndexOptimize  by certificate maintenance_proc_cert  with password ='H@rdP@w0rd';  go  add signature to CommandExecute  by certificate maintenance_proc_cert  with password ='H@rdP@w0rd';  go  add signature to CommandLog  by certificate maintenance_proc_cert  with password ='H@rdP@w0rd';  go  

Now developer1 can run SPECIAL_DatabaseIntegrityCheck successfully. I guess my question is, is there a much simpler way that I'm missing?

Two types of data, so two type of databases?

Posted: 22 Aug 2013 01:32 PM PDT

For a social network site, I need to propose a DB. The application is written in Java & will be hosted on VPS(s) initially.

Broadly classified there is two type of data to be stored at backend:

 1. dynamic lists which are:         - frequently appended to          - frequently read              - sometimes reduced         2. fixed set of data keyed by a primary key(sometimes modified).     "For serving any page, I need to have access to both kind of data!"  

As demanded by every other SN site, we need to consider for easy scaling in the future, but in addition to that our team & resources are also very very limited. We would like to start with a 1 or 2 medium sized VPS(s) & add more servers as data & load grows.

Personally I usually prefer something that is used by a large community, so ofcourse MySQL is big option but it doesn't fit our entire needs. It could be used for 2nd kind of data(among the list above) ie for storing fixed set of columns/data but not ideal for storing dynamic lists(ie 1st kind). So should I use a 2nd database just to fit in only that type of data (two database each containing only data best suited for them)? (Some suggested Cassandra to store the 2nd kind of data.) What is the way to go ?

Oracle to MS SQL Server 2008 Code Conversion Problems [on hold]

Posted: 22 Aug 2013 10:41 AM PDT

      CREATE OR REPLACE FUNCTION CHI_X2 (a1 in number, b1 in number, a2 in number, b2 in number)            RETURN NUMBER IS         DECLARE @tr1 INT;         DECLARE @tr2 INT;         DECLARE @tc1 INT;         DECLARE @tc2 INT;         DECLARE @ca1 INT;         DECLARE @ca2 INT;         DECLARE @cb1 INT;         DECLARE @cb2 INT;         DECLARE @xi INT;         DECLARE @nt INT;           CREATE PROCEDURE ()         AS         BEGIN             SET tr1 = a1+b1           SET tr2 = a2+b2           SET tc1 = a1+a2           SET tc2 = b1+b2           SET nt = tr1+tr2           SET ca1 =(tc1/nt*tr1)           SET ca2 =(tc1/nt*tr2)           SET cb1 =(tc2/nt*tr1)           SET cb2 =(tc2/nt*tr2)           SET xi =((power((a1 -ca1),2)/ca1)+(power((a2 -ca2),2)/ca2)+(power((b1 -cb1),2)/cb1)+(power((b2-cb2),2)/cb2))          return xi          END CHI_X2           CREATE PROCEDURE ()         AS         begin            DECLARE @max_chi INT   DECLARE @xi INT   DECLARE @maxpos INT   DECLARE @n INT   DECLARE @SWV_CUR_OUT_sno VARCHAR(255)   DECLARE @SWV_CUR_OUT_p VARCHAR(255)   DECLARE @SWV_CUR_OUT_t VARCHAR(255)   DECLARE @SWV_cursor_var1 CURSOR   DECLARE @SWV_CUR_IN_sno VARCHAR(255)   DECLARE @SWV_CUR_IN_p VARCHAR(255)   DECLARE @SWV_CUR_IN_t VARCHAR(255)   delete from CH_TABLE   commit   SET @SWV_cursor_var1 = CURSOR  FOR select sessionnumber, sessioncount, timespent from CH_TABLE             order by sessionnumber asc   OPEN @SWV_cursor_var1   FETCH NEXT FROM @SWV_cursor_var1 INTO            @SWV_CUR_OUT_sessionnumber,@SWV_CUR_OUT_sessioncount,@SWV_CUR_OUT_timespent   while @@FETCH_STATUS = 0   begin          SET @max_chi = -999          SET @maxpos = NULL          SET @SWV_cursor_var1 = CURSOR  FOR select sessionnumber, sessioncount, timespent from      CH_TABLE             order by sessionnumber asc          OPEN @SWV_cursor_var1          FETCH NEXT FROM @SWV_cursor_var1 INTO            @SWV_CUR_IN_sessionnumber,@SWV_CUR_IN_sessioncount,@SWV_CUR_IN_timespent          while @@FETCH_STATUS = 0          begin             select   @n = count(*) from(select x1 as x from CH_TABLE union all select x2 from      CH_TABLE) AS TabAl   where x = @SWV_CUR_OUT_sessionnumber or x = @SWV_CUR_IN_sessionnumber          if n = 0         begin            SET xi =                round(CHI_X2(cur_out.sessioncount,cur_out.timespent,cur_in.sessioncount,cur_in.timespent),2)             if xi > max_chi             begin          SET max_chi = xi          SET maxpos = cur_in.sessionnumber            end         end               FETCH NEXT FROM @SWV_cursor_var1 INTO            @SWV_CUR_IN_sessionnumber,@SWV_CUR_IN_sessioncount,@SWV_CUR_IN_timespent          end         if max_chi > -999         begin         INSERT INTO CH_TABLE(X1, X2, VALUE)         VALUES(cur_out.sessionnumber, maxpos, max_chi)               commit     end          CLOSE @SWV_cursor_var1      FETCH NEXT FROM @SWV_cursor_var1 INTO            @SWV_CUR_OUT_sessionnumber,@SWV_CUR_OUT_sessioncount,@SWV_CUR_OUT_timespent   end   CLOSE @SWV_cursor_var1     END  

Hye, there everyone, I'm new to everything here just need to that I have converted the following code into MS SQL SERVER 2008 from Oracle! Now it has some errors though I have done it and NEW to SQL SERVER 2008 Please correct my code;it has some errors! I don't know about how to get rid as I'm new! Please can somebody help me It will be a great effort like a teacher! I will be thankful! Thanks in advance...

Following Expected errors:

Msg 156, Level 15, State 1, Line 1  Incorrect syntax near the keyword 'OR'.  Msg 102, Level 15, State 1, Line 13  Incorrect syntax near '('.  Msg 102, Level 15, State 1, Line 17  Incorrect syntax near '='.  Msg 178, Level 15, State 1, Line 27  A RETURN statement with a return value cannot be used in this context.  Msg 102, Level 15, State 1, Line 28  Incorrect syntax near 'CHI_X2'.  Msg 134, Level 15, State 1, Line 36  The variable name '@xi' has already been declared. Variable names must be unique within a query batch or stored procedure.  Msg 137, Level 15, State 2, Line 49  Must declare the scalar variable "@SWV_CUR_OUT_sessionnumber".  Msg 137, Level 15, State 2, Line 56  Must declare the scalar variable "@SWV_CUR_IN_sessionnumber".  Msg 137, Level 15, State 2, Line 60  Must declare the scalar variable "@SWV_CUR_OUT_sessionnumber".  Msg 102, Level 15, State 1, Line 63  Incorrect syntax near '='.  Msg 102, Level 15, State 1, Line 66  Incorrect syntax near '='.  Msg 137, Level 15, State 2, Line 71  Must declare the scalar variable "@SWV_CUR_IN_sessionnumber".  Msg 137, Level 15, State 2, Line 83  Must declare the scalar variable "@SWV_CUR_OUT_sessionnumber".  Msg 102, Level 15, State 1, Line 86  Incorrect syntax near 'END'.  

Find Duplicate Customers

Posted: 22 Aug 2013 01:50 PM PDT

Okay... I have a table that has customers:

-- Individual Table  * ID (Internal Unique ID)  * IndividualID (External Unique Individual Identifier)  * Last Name  * First Name  * Birth Date  * SSN  * ...  

The issue is that sometimes a person gets multiple Individual ID's. Say the person doesn't provide a SSN for one Encounter, the last name changes, typo in birthday, etc. So you end up with the same person in the individual table multiple times:

1, Frost, Jack, 1/1/2000, 000-00-0008  2, Frost, Jack, 1/1/2000, 000-00-0003  3, Doe,   Jane, 1/1/2000, 000-00-0005  4, Doe,   Janet, 1/1/2000, 000-00-0005  5, Frost, Janet, 1/1/2000, 000-00-0005  

Those are just some examples. The basic idea is that I need to find individuals that are potential matches, so that the right person can merge the individuals into a single account.

The particular query I'm currently on is on SS2008-SP1, but I have other queries on SS2005 through SS2012. Is there any way I can improve this?

Initially I had a single select statement (instead of 2 temp tables, 5 inserts and a select statement), but the "This or This or This or..." took many minutes and this takes ~10 seconds. Population of Customers is ~144k (Select count(*) from Data)

Current I'm using a simple attempt to try and match four parts: Last Name, First Name, DOB, SSN. If 3 or 4 of them match on different individuals, the need to be inspected closer to determine if they really are the same person.

IF object_id('tempdb..#DATA') IS NOT NULL      DROP TABLE #DATA;  GO    CREATE TABLE #DATA (        EXTID VARCHAR(30) NOT NULL      , LNAME VARCHAR(30) NULL      , FNAME VARCHAR(30) NULL      , SSN VARCHAR(11) NULL      , DOB VARCHAR(8) NULL      )  GO    INSERT INTO #DATA  SELECT         EXTID = D1.EXTERNALID      , LNAME = D1.LASTNAME      , FNAME = D1.FIRSTNAME      , SSN = CASE WHEN D1.SSN = '000-00-0000' THEN NULL ELSE D1.SSN END      , DOB = convert(VARCHAR, D1.DOB, 112)  FROM Data D1  WHERE Type = 1 and STATUS = 1  GO    SELECT D1.*, [Splitter] = 'MATCH', D2.*   FROM #Demo D1, #Demo D2 WHERE D1.ID > D2.ID      AND (   D1.LNAME = D2.LNAME          AND D1.FNAME = D2.FNAME          AND D1.SSN   = D2.SSN          AND D1.DOB   = D2.DOB)          UNION  SELECT D1.*, 'LName', D2.*   FROM #Demo D1, #Demo D2 WHERE D1.ID > D2.ID       AND (   D1.LNAME <> D2.LNAME          AND D1.FNAME = D2.FNAME          AND D1.SSN   = D2.SSN          AND D1.DOB   = D2.DOB)          UNION  SELECT D1.*, 'FName', D2.*   FROM #Demo D1, #Demo D2 WHERE D1.ID > D2.ID      AND (   D1.LNAME = D2.LNAME          AND D1.FNAME <> D2.FNAME          AND D1.SSN   = D2.SSN          AND D1.DOB   = D2.DOB)          UNION  SELECT D1.*, 'SSN  ', D2.*   FROM #Demo D1, #Demo D2 WHERE D1.ID > D2.ID      AND (   D1.LNAME = D2.LNAME          AND D1.FNAME = D2.FNAME          AND D1.SSN   <> D2.SSN          AND D1.DOB   = D2.DOB)          UNION  SELECT D1.*, 'DOB  ', D2.*   FROM #Demo D1, #Demo D2 WHERE D1.ID > D2.ID      AND (   D1.LNAME = D2.LNAME          AND D1.FNAME = D2.FNAME          AND D1.SSN   = D2.SSN          AND D1.DOB   <> D2.DOB);  

Edit to add Distinct Counts:

LName   FName   SSN DOB Count  36737   14539   115073  34284   144044  

Edit: Cleaned up a bit to get rid of second temp table. Poking around the Estimated Execution plan, the above query - broken into 5 parts - uses hash map inner joins and takes about 10 seconds. My initial query, and other variations seem to use loop joins and is still chugging along at 10+ minutes.

Redundant transpose. Case is not enough to solve my problem

Posted: 22 Aug 2013 10:22 AM PDT

I have db problem in transposing rows to columns. I am half way through the result but getting redundant data. My table:

EMP_ID  EMP_NAME   SAL_PAID  01      ABC        JAN  01      ABC        FEB  01      ABC        MAR  02      PQR        JAN  02      PQR        MAR  03      XYZ        FEB  

Result Table:

EMP_ID  EMP_NAME   JAN    FEB    MAR    APR  01      ABC         Y      Y      Y      N  02      PQR         Y      N      Y      N  03      XYZ         N      Y      N      N  

I have used case and then the result is as below:

EMP_ID  EMP_NAME   JAN    FEB    MAR    APR  01      ABC         Y      N      N      N  01      ABC         N      Y      N      N  01      ABC         N      N      Y      N  02      PQR         Y      N      N      N  02      PQR         N      N      Y      N  02      PQR         N      N      N      N  03      XYZ         N      Y      N      N  03      XYZ         N      N      N      N  

I have tried this for quite a bit now. Thank you.

Which of these two methods is standard when creating a 1 to many database relationship?

Posted: 22 Aug 2013 02:20 PM PDT

If I have a customer that can have many addresses, I can create an Address table with columns Street, Town etc. and CustomerId. Then I can insert multiple records to have multiple addresses per customer.

Alternatively I can create multiple addresses and give them all the same AddressId, then in my customer table I can have an AddressId (so you'd do SELECT * FROM Address WHERE Address.AddressId = Customer.AddressId).

Which of these is better, is there some reason why you'd use one over the other, or is one of them just silly?

Can scheduled and continous replication configurations exist side-by-side on the same master/slave servers?

Posted: 22 Aug 2013 09:10 AM PDT

Environment

We have a core sql server cluster. This cluster contains some databases that get replicated to a load-balanced sql cluster of currently 3 servers. These databases are replicated each 12 hours but will eventually be replicated every 4 hours.

Requirement

On this cluster a new database is created and we need this database to be replicated asap to the load-balanced sql cluster. A delay of seconds or minutes is allowed and writes to this database are currently and in the future low (a few per hour).

Questions

Can two different replication plans coexist side-by-side on the same environment?

Is it possible to setup a second replication routine for this scenario (continuous transaction replication) besides the current replication schema for the existing databases?

Does this create a high risk for a large existing scheduled replication job?

Our DBA says that this replication scenario creates a high risk for the existing replication configuration (2x a day).

My brainwaves

I can't imagine that this minor write activity with continuous transaction replication can create issues for the large existing replication job. I can imagine the other way around that our continuous replication will suffer twice a day due to the large replication job. We are perfectly fine with that as replication is required ASAP during regular operation.

Where can I find scenarios to work through T-SQL [on hold]

Posted: 22 Aug 2013 08:38 AM PDT

I've been working through the exam guides for the new 70-461 MCSE data exams and i'm at a point where I want to practice my T-SQL. Does anyone know of any good resources whereby scenarios are posed and you have to create a solution through practice. For example, when I learned C# I would work towards a goal of creating a certain type of system or project like a web app or a console app that did a certain thing. I'm struggling to come up with test scenarios to improve my T-SQL experience because I don't have a frame of reference for what professionals in SQL do in their day jobs.

How to make SSMS upper case keywords

Posted: 22 Aug 2013 12:50 PM PDT

I recently started using Management Studio 2012. When using MySQL Workbench, a handy feature was that I could stay all in lower case and any reserved word (like SELECT, INSERT) would convert to upper case automatically. How do I replicate this behavior in SSMS?

Centralize Oracle RMAN scripts in one server

Posted: 22 Aug 2013 01:14 PM PDT

I want to centralize all my Oracle's DB backup shell scripts in one server, and all of them are in different servers, architectures and DB versions. For this purpose I'm going to use the same server where the Recovery Catalog is installed, a rhel6 64bit with 11.2.0.3 DB, and schedule the backup shell scripts via crontab.

This is easily done executing, from the Recovery Catalog server, something like RMAN TARGET SYS@RemoteDBNetIdentifier CATALOG catalogowner@rmanCatalog

Problem is that, according with the compatibility matrix, RMAN client version must match DB target connected version. http://docs.oracle.com/cd/E11882_01/backup.112/e10643/compat003.htm#i634479

$ rman target sys@db_prod_1 catalog rman@rcat    Recovery Manager : Release 11.2.0.3.0 - Production on Jue Ago 22 13:27:52 2013    Copyright (c) 1982, 2011, Oracle and/or its affiliates.  All rights reserved.    Contraseña de la base de datos destino:  el paquete PL/SQL SYS.DBMS_BACKUP_RESTORE versión 11.02.00.01 de la base de datos TARGET no es actual  el paquete PL/SQL SYS.DBMS_RCVMAN versión 11.02.00.01 de la base de datos TARGET no es actual  conectado a la base de datos destino: DB_PROD_1 (DBID=943768957)  Contraseña de la base de datos del catálogo de recuperación:  conectado a la base de datos del catálogo de recuperación    RMAN> exit  

But I don't want to install every single Oracle DB version in the recovery catalog server. So I tried to copy JUST the rman executable from the Oracle DB installations in the others servers to the Recovery Catalog server, but it didn't worked

$ scp oracle@SRV_PROD_1:/usr/oracle/product/11.2.0/bin/rman /usr/oracle/product/rman_bin/11.2.0.1/  rman                                    100%   14MB 209.6KB/s   01:06    $ cd product/rman_bin/11.2.0.1/  $ ./rman target sys@db_prod_1 catalog rman@rcat    Recovery Manager : Release 11.2.0.1.0 - Production on Jue Ago 22 13:51:27 2013    Copyright (c) 1982, 2009, Oracle and/or its affiliates.  All rights reserved.    RMAN-00571: ===========================================================  RMAN-00569: =============== ERROR MESSAGE STACK FOLLOWS ===============  RMAN-00571: ===========================================================  RMAN-00554: fallo al inicializar el paquete del gestor de recuperación interno  RMAN-03000: fallo al inicializar el componente compilador del gestor de recuperación  RMAN-06035: versión incorrecta de recover.bsq; se esperaba 11.2.0.1 y se ha encontrado 11.2.0.3  

It seems that I'd also need the recover.bsq file (which is in $ORACLE_HOME/ADMIN), but I want to be sure that I wont miss more files or face new problems when we'll have to perform a disaster recovery or something in the future.

What can I do?

How can I only install the different versions of RMAN client? There's another method to centralize all the backups work (I think that EM Cloud Control can achieve this, I didn't read about it, just figuring out, but we dont want to rely on a GUI web-based application to manage our backup strategy.)

Regards

Inline edit SQL Server database rows from Visual Studio

Posted: 22 Aug 2013 05:13 PM PDT

I'm pretty sure Microsoft have pulled one of the most useful features for performing quick edits on a SQL Server Database within the Visual Studio IDE. It seems to have only affected SQL 2012 instances, but from the Server Explorer I can no longer right click on a table "Show Table Data", pop open the SQL pane, query the data then perform inline edits on the results (as if I were modifying a spreadsheet).

Show Table Data

This means I now need to go into SSMS to make these kind of quick updates. Does anybody know of a plugin I can use with VS 2012 to bring back this functionality? It seems odd to me that Microsoft have two different development trajectories with SSDT and SSMS? Are they designed to serve different purposes? Can SSMS be integrated into the Visual Studio IDE? I'd rather have a unified development environment if possible.

Any thoughts on a workaround for this problem would be much appreciated.

EDIT

I know some purists would quiver at the thought of treating a database table like a spreadsheet, but semantically they are not a world apart, plus this is supported in SSMS. I'm more in favour of relying on GUI based approaches where I can to speed up routine tasks, why some would balk at this I have no idea?

Dealing with data stored as arrays in a MySQL DB

Posted: 22 Aug 2013 08:14 PM PDT

So I know storing arrays in a DB field is wrong and would never do it myself, however a 3rd party plugin my company is using stores data in an array and I was wondering if you could help me try to deal with it.

It basically seems to link 2 tables and add a view count. Here is an example of the data:

a:4:{i:4;i:196;i:26;i:27;i:5;i:155;i:34;i:4;}

So I think this means there are 4 entries in the array, each with 2 attributes. The first - i.e. 4, 26, 5, 34 are "store codes". The second lot (196, 27, 155, 4) are number of plays. God knows why they are stored like this as there is already another table that links the video with the stores and they could've just stuck another column there for view count.

Anywho, what I want to do is order by view count based on store id within that array. Do you think this is possible and does anyone have any ideas how to do this? If storing data like this is a standard, do you know the name for it as I could probably take it from there?

Thanks!

Unable to connect oracle as sysdba tables have been dropped

Posted: 22 Aug 2013 11:13 AM PDT

I have a script which lists all tables belonging to the user and executes DROP for all of them.

By mistake, I logged in oracle with 'sys as sysdba' and ran above script. Due to which all sysdba tables are dropped.

Now i can not startup database instance. In alert log, it gives following error:

Sat Jul 20 15:28:21 2013

Errors in file orcl_ora_4276.trc:

ORA-00942: table or view does not exist

Error 942 happened during db open, shutting down database

USER: terminating instance due to error 942

I tried to flashback one droppd table, but it is giving error:

SQL> alter database open;

alter database open

*

ERROR at line 1:

ORA-01092: ORACLE instance terminated. Disconnection forced

SQL> FLASHBACK TABLE MAP_OBJECT TO BEFORE DROP;

ERROR:

ORA-03114: not connected to ORACLE

Please suggest if there is any way to restore all these tables. Or if creating new database is the only way?

Analyse MySQL General Query Log in Real-time?

Posted: 22 Aug 2013 06:13 PM PDT

We want to use mysql general query log to do real-time monitoring and auditing.

Currently our approach is:

  • set general_log=on;
  • sleep 15m;
  • set general_log=off;
  • scp & rm xxx.log;
  • set general_log=on;...

But the main problem is when turn on/off general log it'll cause a peak of slow query.

I also thought of another approach: turn on genlog; tail -f it and send out the log; periodically truncate the logfile (with "> xxx.log" or "cat /dev/null >xxx.log").

I'm wondering whether it's practical.

If only mysql would provide some built-in general log message queue stuff...

Mysql settings for query_cache_min_res_unit

Posted: 22 Aug 2013 12:13 PM PDT

What is the best setting for query_cache_min_res_unit for these results:

+-------------------------+-----------+  | Variable_name           | Value     |  +-------------------------+-----------+  | Qcache_free_blocks      | 35327     |  | Qcache_free_memory      | 295242976 |  | Qcache_hits             | 236913188 |  | Qcache_inserts          | 49557287  |  | Qcache_lowmem_prunes    | 0         |  | Qcache_not_cached       | 7128902   |  | Qcache_queries_in_cache | 195659    |  | Qcache_total_blocks     | 426870    |  +-------------------------+-----------+  

Do I need to change any other settings?

My website creates very large results. This is the current setting:

query_cache_min_res_unit = 4096  

Info on the mysql dev website

If most of your queries have large results (check the Qcache_total_blocks and Qcache_queries_in_cache status variables), you can increase performance by increasing query_cache_min_res_unit. However, be careful to not make it too large (see the previous item).

DB2 db2fm proccess

Posted: 22 Aug 2013 07:13 PM PDT

Server is been up for 365 days, however i got some weird repeated procceses.

Are these normal?

ps -fea | grep db2fm

  db2inst1  643284  229516  29   May 25      - 212564:06 /home/db2inst1/sqllib/bin/db2fm -i db2inst1 -m /home/db2inst1/sqllib/lib/libdb2gcf.a -S  db2inst1  671770  229516  56   May 14      - 227447:02 /home/db2inst1/sqllib/bin/db2fm -i db2inst1 -m /home/db2inst1/sqllib/lib/libdb2gcf.a -S  db2inst1  757794 1237058   0   Apr 19  pts/7  0:00 /bin/sh /home/db2inst1/sqllib/bin/db2cc  db2inst1  774232  229516  30   Sep 25      - 94218:54 /home/db2inst1/sqllib/bin/db2fm -i db2inst1 -m /home/db2inst1/sqllib/lib/libdb2gcf.a -S  db2inst1  962750  229516  30   Jul 18      - 145256:01 /home/db2inst1/sqllib/bin/db2fm -i db2inst1 -m /home/db2inst1/sqllib/lib/libdb2gcf.a -S  db2inst1  999450  229516  29   Aug 17      - 117710:27 /home/db2inst1/sqllib/bin/db2fm -i db2inst1 -m /home/db2inst1/sqllib/lib/libdb2gcf.a -S  db2inst1 1179898  229516  58   Nov 02      - 75788:49 /home/db2inst1/sqllib/bin/db2fm -i db2inst1 -m /home/db2inst1/sqllib/lib/libdb2gcf.a -S  

ps -fea | grep db2agent

  db2inst1  409770  680100   0   Apr 19      -  0:00 db2agent (DATABASEA) 0  db2inst1  450750  778412   0   Apr 18      -  0:03 db2agent (idle) 0  db2inst1  618688  680100   0   Apr 19      -  0:00 db2agent (idle) 0  db2inst1  651440  680100   0   Nov 17      -  0:20 db2agent (DATABASEA) 0  db2inst1  655508  491676   0   Apr 19      -  0:04 db2agent (idle) 0  db2inst1  684038  680100   0   Mar 23      -  0:03 db2agent (DATABASEA) 0  db2inst1  790706  491676   0   Apr 19      -  0:00 db2agent (idle) 0  db2inst1  880672  680100   0   Apr 19      -  0:00 db2agent (DATABASEA) 0  db2inst1  913438  778412   0   Nov 16      -  0:20 db2agent (idle) 0  db2inst1  946182  491676   0   Apr 19      -  0:00 db2agent (DATABASEA) 0  db2inst1  991312  778412   0   Apr 17      -  0:16 db2agent (idle) 0  db2inst1 1077466  491676   0   Apr 19      -  0:00 db2agent (DATABASEA) 0  db2inst1 1134726  680100   0   Apr 19      -  0:00 db2agent (DATABASEA) 0  db2inst1 1142964  491676   0   Apr 19      -  0:00 db2agent (idle) 0  db2inst1 1233112  491676   0   Apr 19      -  0:00 db2agent (idle) 0  db2inst1 1261748  778412   0   Jun 15      -  0:18 db2agent (idle) 0  db2inst1 1384678  778412   0   Mar 23      -  0:27 db2agent (idle) 0  db2inst1 1404936  680100   0   Apr 19      -  0:00 db2agent (DATABASEA) 0  db2inst1 1421368  778412   0   Mar 22      -  0:04 db2agent (idle) 0  db2inst1 1445936  491676   0   Apr 19      -  0:00 db2agent (DATABASEA) 0  db2inst1 1482864  491676   0   Jun 16      -  0:31 db2agent (idle) 0  db2inst1 1503440  778412   0   Jun 15      -  0:56 db2agent (idle) 0  db2inst1 1519842  778412   0   Mar 23      -  0:00 db2agent (DATABASEA) 0  db2inst1 1531946  680100   0   Apr 19      -  0:00 db2agent (idle) 0  db2inst1 1572884  680100   0   Apr 19      -  0:00 db2agent (idle) 0  

Other info

  oslevel -g  Fileset                                 Actual Level        Maintenance Level  -----------------------------------------------------------------------------  bos.rte                                 5.3.0.40            5.3.0.0    db2fm -s -S  Gcf module 'fault monitor' is NOT operable  Gcf module '/home/db2inst1/sqllib/lib/libdb2gcf.a' state is AVAILABLE      uptime    02:14PM   up 365 days,  12:51,  6 users,  load average: 6.69, 6.89, 6.97     db2level  DB21085I  Instance "db2inst1" uses "64" bits and DB2 code release "SQL08020"  with level identifier "03010106".  Informational tokens are "DB2 v8.1.1.64", "s040812", "U498350", and FixPak "7"    

How to snapshot or version a relational database when data changes?

Posted: 22 Aug 2013 04:13 PM PDT

My system receives data feeds. Each data feed will end up creating inserts and/or updates to most tables in the (relational) database.

I need to capture the snapshot of what the entire database looked like after each data feed is received. Basically I need a way to version the database each time a data feed is run through the system.

Note, by capturing a snapshot, I dont mean literally taking a snapshot of the database, but rather writing history records or some such mechanism so that I can query the database across "versions" to see what changed between versions (among other use cases)

Do known data model designs exist that can capture a snapshot of a database version like this?

Generic SQL Job Scheduler for multiple RDBMS's?

Posted: 22 Aug 2013 08:13 AM PDT

I have been searching for an answer to this, but can't seem to find anything. So my problem is this - we have an environment with MS SQL Server 2008, MySQL, and RedShift, and have some complex dataflows between the databases. Right now, the scheduling is done through independent systems, but I want to have one scheduler that controls the dataflows from beginning-to-end, and is able to script flows from MS SQL to RedShift, etc. Is there a system that can accomplish this already? I'm not a DBA, so I am guessing someone has had this problem before...

Thanks in advance!

EDIT: So one of our dataflows might look like this - file posted on SFTP --> run normal ETL routines --> compile final complete file --> send to customer/push to S3 --> Run SQL commands on Redshift to load* --> Nightly batch processing on RedShift* --> Unload to S3* --> Load into MySQL*

*These are manually run using a tool that just connects via jdbc (can't remember the program)

My DB-related experience is very light, so I was about to write some python scripts and schedule them in CRON, but that is custom and hard to expand - surely someone has had this problem before. We would like to be able to see a status of the job in one place, create new dataflows/ETL's between all three systems (like an SSIS job).

Login failed for user Error: 18456, Severity: 14, State: 11

Posted: 22 Aug 2013 10:13 AM PDT

I have an AD group XYZ that I have added to SQL Server security with data_reader permissions.

The XYZ group has around 10 users in there who are successfully able to access the SQL Server database. I recently added a new user to this group (at AD level), but this person is not able to access SQL Server (through Mgmt Studio) and he's getting the error below

Login failed for user. Reason: Token-based server access validation failed with an infrastructure error. Check for previous errors.

Error: 18456, Severity: 14, State: 11.

I have already verified AD permissions are setup properly, user has restarted his machine, he is not part of any group that has DENY access and the SQL Server XYZ group has been removed and readded to the SQL Server instance in Mgmt Studio and server has been restarted.

Any ideas on how to proceed further?

Thanks!

Rent weekly cost database design

Posted: 22 Aug 2013 03:13 PM PDT

I have a database which contains a table BUILDING with in each row details about some building, another table BUILDING_UNIT contains rows with details about a single building unit which refers with a foreign key to the belonging BUILDING.ID. The BUILDING_UNIT table also refers to a table CATEGORY which tells whether the BUILDING_UNIT is of category A,B,C,D again with a foreign key pointing to CATEGORY.ID.

Now the final cost of renting the building unit depends on its building, category and on the number of days it is rented and specific period of the year. We only rent them weekly so I might as well use weeks only however I'd like it to be as flexible as possible in the future.

I cannot convince myself on a table which can represent this situation.

Do I have to use a table with coefficients for each day of the year and then a table with coefficients for A,B,C,D and then a table with coefficients for each Building and then somehow calculate a result?

Is there some standard and recognized implementation for problems of this type?

Thank you

EDIT: Notice the solution should abstract from the formula for calculating the cost which might change in the future. However I might be asked to make a specific week of the year, for building unit X inside building Y to cost 300$ while the week after 600$. Generally building units inside the same building and in the same week cost the same, however that might change in future so I'd like to treat already all specific cases.

Proper procedure for migrating a MySQL database to another Debian machine?

Posted: 22 Aug 2013 02:13 PM PDT

I have one server running an older Debian version with MySQL 5.x and a newer Debian server, also running MySQL.

I've created a backup of all databases on the first server like so:

mysqldump -uuser -ppass --all-databases > dump.sql  

On the other server, I did a:

mysql -uuser -ppass < dump.sql  

At first, everything seemed great. I could browse my databases in phpMyAdmin, but as soon as I tried logging in again, it failed. Turns out, my root password had been overwritten with the one from the older database.

I wanted to reset it, but in order to do so, I would have needed to start mysqld_safe. Which I couldn't because the password for the debian-sys-maint user had been overwritten as well in the database. When I thought all hell had broken loose, I somehow reset both the root and debian-sys-maint passwords to the original values of the new server, and I managed to revert to a clean state.

Since I obviously don't want to go down that road again, here's the question(s):

  • Was I right with my approach of using a complete --all-databases dump?
  • Was there something I needed to do in advance to reading in that dump to prevent this desaster from happening? Or even before creating the dump?

If I'm going about this the wrong way:

  • What is the proper procedure for migrating all databases and their users to another server?

Note that I'm not that experienced with MySQL and server administration at all, so I might be missing something obvious. All the tutorials and how-tos I've found never mention anything like this and just talk about importing the complete dump.

How to add 'root' MySQL user back on MAMP?

Posted: 22 Aug 2013 01:13 PM PDT

On PhpMyAdmin, I removed 'root' user by mistake. I was also logged in as 'root'. How can I add the user 'root' back, on MAMP?

Slow insert with MySQL full-text index

Posted: 22 Aug 2013 09:13 AM PDT

I use a full-text index in a MySQL table, and each insert into this table takes about 3 seconds. It seems that MySQL rebuilds (a part) of the full text index after each insert/update. Is this right?

How can I get better performance from the INSERT? Is there perhaps an option to set when MySQL rebuilds the full-text index?

[MS SQL Server] SSIS Question Help

[MS SQL Server] SSIS Question Help


SSIS Question Help

Posted: 22 Aug 2013 03:13 AM PDT

Hi Guys, I have question. I am creating a SSIS Package, Its runs fine with no problem, Its kinda simple package, Let me explain...Pulling the data from SQL Table and my destination is flat file (First flat file). Here i want one more logicI want to create one more flat file with below information1) Count from First flat file2) Flat file name (Naming convention change "Flatfilename_getdate()" from first flat file3) Time when Package run..Is anyone can help me

Server reboot...missing drives

Posted: 22 Aug 2013 01:00 AM PDT

Last weekend we applied some updates on a prod server and rebooted it. After the reboot when we connect to the server, two of the databases went to suspect mode. Later realized the log file drive got disconnected. Had to rescan the disks and reboot again in order to bring back the databases up. We want to avoid this issue in future. What's the reason behind this behavior and how to fix it ? OS- Windows server 2008R2 SP1SQL- SQL server 2008 sp3

Unistall Named Instance Only

Posted: 22 Aug 2013 03:59 AM PDT

We have a named instance of SQL Server 2008 R2 which was installed to support a single application. The instance is on a server that also has a default instance hosting databases for several other applications.The application using the named instance (named for the application) is no longer used. Is it safe to uninstall the named instance without risk of damaging the default instance, or are we better just off opening SQL Configuration Manager and setting the Startup Mode of the named instance to "Disabled?"

Multi node multi instance clustering Drive letters

Posted: 22 Aug 2013 12:52 AM PDT

we have a two node one instance cluster in our environment. Planning to make it multi node multi instance. Currently on each instance we have around 8 different drives. We are thinking of 4 node 3 instance clustering, so total drives will be around 24 drives. But as I see there are only 17 drive letters to choose from. How to configure the 4 node 3 instance cluster with all 24 drives ?

xml file creation and auto updation from sql database

Posted: 21 Aug 2013 04:43 PM PDT

Hi,we are trying to generate xml file to a particular location from sql server 2008 tables and we want to auto update that xml file on a particular time intervals at that location only (as sql data updated we need auto updation of that xml file).

Doubts about dbcc shrinkfile working

Posted: 21 Aug 2013 07:04 PM PDT

Hi friends i wanted to know about behaviour of dbcc shrinkfile command dbcc shrinkfile(2,10)now 2 denotes that i want to shrink log file but what i wanted to know about is size to which it decrease.It know size is in 10 mb.But what i wanted to know is whether size would reduce by 10 mb or reduce to 10 mb.for eg suppose log file size is 100 mb.then after executing above command would log file new size would be 10(100mb to 10mb) mb or 90 mb(100mb-10mb)Thanks and RegardsAnoop ps. I know shrinking is bad but still want to know about it

[Articles] The Costs of Data

[Articles] The Costs of Data


The Costs of Data

Posted: 21 Aug 2013 11:00 PM PDT

Information is free, but data certainly has a cost. Especially as there are real costs to storing and managing large volumes of bits and bytes.

sqldbabundle Top 5 Hard-earned Lessons of a DBA
'10 Tips for Efficient Disaster Recovery' by Steve Jones. Prepare for any future disaster by reading Steve's tips today.

Search This Blog