Saturday, April 27, 2013

[SQL 2012] Use only SSIS 2012 with dbs left on 2008R2

[SQL 2012] Use only SSIS 2012 with dbs left on 2008R2


Use only SSIS 2012 with dbs left on 2008R2

Posted: 26 Apr 2013 01:35 PM PDT

Hello,I have a client that is not ready to migrate to SQL Server 2012, and actually just finished a migration to 2008R2. Our licenses grant us to SQL 2012, but downgraded to match the production environment. My question is: Are there any possible negative side-effects to using only the SSIS portion of 2012, but using the SQL server half of 2008.Main driver: Allow tighter/easier TFS integration with VS 2010, to move away from VS2008. Plus, a lot of the features in SSIS 2012 would help solve some pain points we've seen in our ETLs.Thanks!!!

How to uninstall SSAS

Posted: 26 Apr 2013 05:14 AM PDT

I've been tasked with uninstalling SSAS from our SQL Server 2012 instance and re-installing it with the Multidimensional mode rather than Tabular. I cannot find a way to uninstall just SSAS. Does anyone have any clues on this?Thanks,Gina

[SQL server issues] Created Issue: New to datawarehousing...and want to know how the Adventurework and AdventureworkDW has been developed [17881]




description



New to datawarehousing...and want to know how the Adventurework and AdventureworkDW has been developed..
how the OLTP data has been extracted to AdventureworksDW..datawarehouse system and need some design documents....what to know how the DIM tables are created...and everything







.

sqlserversamples.codeplex.com

[T-SQL] output understanding for most memory reads?

[T-SQL] output understanding for most memory reads?


output understanding for most memory reads?

Posted: 27 Apr 2013 12:03 AM PDT

Hi..Top procedures memory consumption per execution as below capture script[code="sql"]SELECT TOP 100 *FROM ( SELECT DatabaseName = DB_NAME(qt.dbid) ,ObjectName = OBJECT_SCHEMA_NAME(qt.objectid,dbid) + '.' + OBJECT_NAME(qt.objectid, qt.dbid) ,DiskReads = SUM(qs.total_physical_reads) -- The worst reads, disk reads ,MemoryReads = SUM(qs.total_logical_reads) --Logical Reads are memory reads ,Executions = SUM(qs.execution_count) ,IO_Per_Execution = SUM((qs.total_physical_reads + qs.total_logical_reads) / qs.execution_count) ,CPUTime = SUM(qs.total_worker_time) ,DiskWaitAndCPUTime = SUM(qs.total_elapsed_time) ,MemoryWrites = SUM(qs.max_logical_writes) ,DateLastExecuted = MAX(qs.last_execution_time) FROM sys.dm_exec_query_stats AS qs CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS qt GROUP BY DB_NAME(qt.dbid), OBJECT_SCHEMA_NAME(qt.objectid,dbid) + '.' + OBJECT_NAME(qt.objectid, qt.dbid)) TORDER BY IO_Per_Execution DESC[/code]as below outputs, how can understand these numbers? which is normal or critical? Logical Reads means, data read from memory cache is too high number. ( how can reduce? By using proper indexing)output------Memory Reads: 104131 Total IO Reads: 104155 (Executions: 1505IO_Per_execution: 557CPU Time: 215258DiskWaitAndCPUTime: 215272Memory writes: 2Thanksananda

Dynamic export to flat files by date

Posted: 26 Apr 2013 07:42 AM PDT

Hello all,I am tasked with archiving some very large tables. There are about 30 tables that I need to do work on. I need the tables to be exported to pipe-delimited text files. Because of the size of the tables, I also need to split the tables by date to keep the size down. Most of the tables have a date field, the ones that do not are smaller and I can just export them to one file.The tables that have the date fields I need to split out by YYYYMM.Can anyone help me with the best approach to take with this?

Error when Cascade Update on child tables

Posted: 26 Apr 2013 08:31 PM PDT

HiThere is a DB with 4 tables (3 master tables and one is detail which has daily information)Table "a" is master table contains 2 fields:a_code (primary key)a_nameTable "b1" is master table contains 3 fields:a_code (primary key)b1_code (primary key)b1_nameTable "b2" is such as table"b1". b2 is master table contains 3 fields:a_code (primary key)b2_code (primary key)b2_nameTable "C" is detail table contains 5 fileds:a_code (primary key)b1_code (primary key)b2_code (primary key)C_code (primary key)C_nameField "a_code" is primary key in table "a" and also it is foreign key in tables "b1" and "b2".b1_code and b2_code are a part of primary key in their tables and are also foreign key in tables "C".Now we wants create a Relation between tables. So that table C be Related with b1 and b2 then tables b1 and b2 Related with a.In other words, table c is sub table of b1 and b2. And tables b1 and b2 are sub tables of a.In other hands, table a is first level . tables b1 and b2 are in second level and table c is in third level.Now it is necessary select Cascade for update fields.First question:Table c has 2 Relations . one Relation with table b1 and another Relation with b2. But only one Relation can de cascade for update. The second Relation will be faced to error.Error:'b2' table saved successfully'c' table- Unable to create Relationship 'FK_c_b2'. Introducing FOREIGN KEY constraint 'FK_c_b2' on table 'c' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.Could not create constraint. See previous errors.Second question:The code fields which are primary keys (a_code, b1_code, b2_code, c_code). They are hidden for user. User can not view them. When you add new record to table , the code field will be creased automatically. on the other hand the field "a_code" not necessary to be changed when you edit field "a_name". therefore it is not necessary to create Relation and also to set Cascade update to child tables. Now I want to ask, is my DB a standard DB in this case?Third question:Field a_name can provide my aim . therefore what is necessary to field a_code? In a standard DB field a_code must be created or not?Thanks very much

Insert statement error?

Posted: 26 Apr 2013 05:35 PM PDT

Hi,what is wrong this code? pl. suggest[code="sql"] create table databaseSize ( DatabaseName varchar (100), RowSizeMB varchar (50), LogSizeMB varchar(50), DBSizeGB varchar (50), SteamSizeMB varchar(50), TextIndexSizeMB varchar(50), time_stamp getdate()) insert into databaseSize ( 'DatabaseName', 'RowSizeMB', 'LogSizeMB', 'DBSizeGB', 'SteamSizeMB', 'TextIndexSizeMB', 'time_stamp') SELECT DB_NAME(db.database_id) DatabaseName, (CAST(mfrows.RowSize AS FLOAT)*8)/1024 RowSizeMB, (CAST(mflog.LogSize AS FLOAT)*8)/1024 LogSizeMB, (CAST(mfrows.RowSize AS FLOAT)*8)/1024/1024+(CAST(mflog.LogSize AS FLOAT)*8)/1024/1024 DBSizeG,(CAST(mfstream.StreamSize AS FLOAT)*8)/1024 StreamSizeMB, (CAST(mftext.TextIndexSize AS FLOAT)*8)/1024 TextIndexSizeMB FROM sys.databases db LEFT JOIN (SELECT database_id, SUM(size) RowSize FROM sys.master_files WHERE type = 0 GROUP BY database_id, type) mfrows ON mfrows.database_id = db.database_id LEFT JOIN (SELECT database_id, SUM(size) LogSize FROM sys.master_files WHERE type = 1 GROUP BY database_id, type) mflog ON mflog.database_id = db.database_id LEFT JOIN (SELECT database_id, SUM(size) StreamSize FROM sys.master_files WHERE type = 2 GROUP BY database_id, type) mfstream ON mfstream.database_id = db.database_id LEFT JOIN (SELECT database_id, SUM(size) TextIndexSize FROM sys.master_files WHERE type = 4 GROUP BY database_id, type) mftext ON mftext.database_id = db.database_id ORDER BY 4 DESC [/code]thanksananda

datetime comparison behaving oddly

Posted: 26 Apr 2013 07:42 AM PDT

I think I'm about to fill a gap in my knowledge base, because I've been banging my head against this all day and I'm baffled. I'm going to provide as simplified a version as possible for illustration purposes.OBS is a table that contains a variety of observations for hospital patients. The field in which the observation is stored is a varchar(2000) called OBSVALUE. This can contain just about anything - in many cases, it contains a date. These are the values I'm interested in.Now for some code:[code="sql"]WITH cte_OBS AS ( SELECT CAST(OBSVALUE AS datetime) AS OBSVALUE FROM OBS WHERE ISDATE(OBSVALUE) = 1)SELECT OBSVALUEFROM cte_OBSWHERE OBSVALUE < GETDATE()[/code]If I execute the contents of the CTE, I get 66350 rows. If I execute the entire thing except for the WHERE clause, I get 66350 rows. If I execute everything including the WHERE clause, I get:[code="plain"]Msg 241, Level 16, State 1, Line 1Conversion failed when converting date and/or time from character string.[/code]The same thing happens if I replace GETDATE() with CAST('4/1/2013' as datetime) or CONVERT(datetime,'4/1/2013'). I'm totally stumped. Can anyone enlighten me?thanks!ron

Nested Stored Procedure does not work as expected

Posted: 26 Apr 2013 07:12 AM PDT

I have 2 Stored Procedures Procedure A and Procedure B.Both Procedures have @year as parameter and if no parameters passed take the current year as an input parameter.Procedure B is called within Procedure ABut Procedure B does not work as expected. ********THERE ARE NO ERRORS when I say PROCEDURE B does not work ********.Everything compiles and executes fine.If the Procedure B is executed as standalone or isolated it works fine and inserts data.But when used in nested mode it works only for Previous year i.e @year-1 for second run , but does not work for current year.It work for current year only when run as isolated or stanalone and inserts data into a table.The syntax for procedure is as belowCREATE PROCEDURE [Procedure A] @Year int = nullWITH EXECUTE AS 'Domain\user'ASIF (@Year is null) BEGIN SET @Year = (Select top 1 year from table where type= 'CurrentYear') END@LastYear = @Year -1 EXEC Procedure B @Year = @Year /* DOes Not work with nested ( no data inserted).Works only when executed as standalone ( data gets inserted) */EXEC Procedure B @Year = @LastYear /* works in nested mode only when the nested SP is ran twice.Also works standalone */THere are many other SP's within Procedure A and all work fine.

[SQL server issues] Created Issue: SQL Server 2008 Developer edition sample database install error [18174]







description



I'm trying to install Adventureworks sample dB and i get an error.
I successfully downloaded the mdf file however when attach, add and click OK from SSMS I get the error:
 
Msg 5172, Level 16, State 15, Line 1
The header for file 'C:\Program Files\Microsoft SQL Server\AdventureWorks2012_Data.mdf' is not a valid database file header. The FILE SIZE property is incorrect.







.

sqlserversamples.codeplex.com

[SQL server issues] Created Issue: AdventureWorksDW2012 Download file corrupt [19063]

There seams to be an issue with the AdventureWorksDW2012 Data file download. When I try to run this SQL statement:

CREATE DATABASE AdventureWorksDW2012 ON (FILENAME = 'E:\MSSQL11.SQL02\MSSQL\DATA\AdventureWorksDW2012_Data.mdf') FOR ATTACH_REBUILD_LOG;

This is the error I get:

Msg 5172, Level 16, State 15, Line 1
The header for file 'E:\MSSQL11.SQL02\MSSQL\DATA\AdventureWorksDW2012_Data.mdf' is not a valid database file header. The FILE SIZE property is incorrect.

Thanks,Dan

There seams to be an issue with the AdventureWorksDW2012 Data file download. When I try to run this SQL statement:

CREATE DATABASE AdventureWorksDW2012 ON (FILENAME = 'E:\MSSQL11.SQL02\MSSQL\DATA\AdventureWorksDW2012_Data.mdf') FOR ATTACH_REBUILD_LOG;

This is the error I get:

Msg 5172, Level 16, State 15, Line 1
The header for file 'E:\MSSQL11.SQL02\MSSQL\DATA\AdventureWorksDW2012_Data.mdf' is not a valid database file header. The FILE SIZE property is incorrect.

Thanks,Dan


.

sqlserversamples.codeplex.com

[SQL Server 2008 issues] Renaming system databases

[SQL Server 2008 issues] Renaming system databases


Renaming system databases

Posted: 26 Apr 2013 07:10 PM PDT

Can I rename the physical name of both mdf and ldf files of system databases such as msdb,model and master?

read txt file

Posted: 26 Apr 2013 05:00 PM PDT

hello all.i use this T-Sql for reading txt file:select * from OpenDataSource( 'Microsoft.ACE.OLEDB.12.0','Data Source="f:\rahnama.txt";Extended properties="Text;hdr=no"')...rahnama#txtbut gets error:OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)" returned message "'f:\rahnama.txt' is not a valid path. Make sure that the path name is spelled correctly and that you are connected to the server on which the file resides.".Msg 7303, Level 16, State 1, Line 4Cannot initialize the data source object of OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)".what is the problem?what do you do?

Sql Books

Posted: 26 Apr 2013 04:25 PM PDT

I have series of following books but i have not gone through those books yet. I am planning on reading them now. But i am thinking as 2012 is already out. Do you guys think that there is so much changes between sql 2005 and 2008R2/2012([b]in terms of content of these books[/b])?Is it good idea to read those books when sql 2012 is already out? Can someone tell me what are the features which are deprecated in sql 2008 R2 and sql 2012 and i do not need to learn from these books?Inside SQL Server 2005: TSQL Querying Inside SQL Server 2005: TSQL Programming Inside SQL Server 2005: The Storage EngineInside SQL Server 2005: Query Tuning and OptimizationThanks so much

System can't file specified

Posted: 26 Apr 2013 02:51 PM PDT

I am working on creating peer-to-peer replication testing.I have created Peer publication from DEV-> DBTEST. All log reader agent job working to be fine on DEV but it give me error on DBTEST as follow.Any help should be greatly appreciated. Please let me know if more information is required.Executed as user: sqlservices. Replication-Replication Transaction-Log Reader Subsystem: agent DBTEST-Test_PeerReplication-8 failed. The system cannot find the file specified. The step failed. [SQLSTATE 42000] (Error 14151). The step failed.When i click on Publication -> View Log Reader Agent Status , it throw me an error System can't find the file specified. I am not sure how to set this file up.

convert xml into csv

Posted: 26 Apr 2013 07:13 AM PDT

I'm looking for an easy way to either convert xml to csv. I've tried using the SSIS xml source package way and I'm getting all kinds of truncation errors. Thanks in advance.

using NOLOCK in views

Posted: 26 Apr 2013 05:40 AM PDT

I've done a lot of reading on using WITH NOLOCK and understand the pitfalls. We have a situation where our nightly UPDATE process will get blocked by somebody. The other day it was a spotfire query that wasn't doing anything - but for some reason had kept a connection open since 12 hours before. A few weeks ago it was a PC SAS query that the user had killed but again for some reason had kept a connection to the database and held a lock which caused our nightly process to wait all night until we killed the transaction the next morning. We don't allow any updates during the day. So one argument of dirty reads if using WITH NOLOCK won't be an issue. We are not trying to use WITH NOLOCK to fix concurrency problems of transactions not committing either. It's just these random "read" transactions that will get hung for some reason and keep a lock. Would our idea of coding all VIEW's using the WITH NOLOCK work in preventing these errors? All access to our database is done via views. So anybody reading during the day (with PC SAS, spotfire, etc...) would not be taking any locks. If they got hung for some reason, there would not be any locks to get in the way of our nightly UPDATE process. Looking for opinions? We don't really have any way of testing because we can never recreate these hung transaction situations.

concerns using linked server -security.

Posted: 26 Apr 2013 09:47 AM PDT

We are designing of an application that using backend SQL database. When records are inserted into a SQL table, we also wanted to update records in an oracle database. The plan is to using linked server in SQL , and create an trigger when SQL server records are updated, then Oracle will be updated too.We don't use linked servers in our environment for Security reasons, but if it is needed we have to go this route. Any recommendations for security of linked server?Thanks,

WHILE loop to relieve contention in an update

Posted: 26 Apr 2013 07:31 AM PDT

We have a situation where the business requires some ETL to be done throughout the day on a production database. One of the procs updates an xml column for a set of rows. The developer has decided to change this proc to do a while loop and update row by row to relieve page contention and only take a row lock. Is this a good idea when speed of the proc is not a concern? Also, this is a while loop with a counter, not a cursor... so should this maybe be a cursor instead of a while loop?

Migration 2005 TO 2008 R2

Posted: 26 Apr 2013 09:00 AM PDT

Hello,I have recently migrated one database from 2005 which was running on sql server 2000 compatibility to sql server 2008 R2. I have couple of maintenance plans which clean up the backup files which are older than 23 hours. I am getting the following error while running the daily maintenance job:Code: 0xC002F210 Source: {BE15E2A4-4E27-4617-85FC-769FA40B8C15} Execute SQL Task Description: Executing the query "DECLARE @Guid UNIQUEIDENTIFIER EXECUTE msdb..sp..." failed with the following error: "The INSERT statement conflicted with the FOREIGN KEY constraint "FK_sysmaintplan_log_subplan_id". The conflict occurred in database "msdb", table "dbo.sysmaintplan_subplans", column 'subplan_id'. The statement has been terminated.". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly. End Error Code: 0xC0024104 Source: Maintenance Cleanup Task Description: The Execute method on the task returned error code 0x80131501 (An exception occurred while executing a Transact-SQL statement or batch.). The Execute method must succeed, and indicate the result using an "out" parameter. End Error Error: Code: 0xC0024104 Source: {C1CAE90D-B745-4E00-B5DD-9A31CF44895F} Description: The Execute method on the task returned error code 0x80131501 (An exception occurred while executing a Transact-SQL statement or batch.). The Execute method must succeed, and indicate the result using an "out" parameter. End Error DTExec: The package execution returned DTSER_FAILURE (1). The package execution failed. The step failed.I have checked the msdb database but there is not table called dbo.sysmaintplan_subplans both is 2005 and 2008 R2. But the job was running fine in 2005 which was running in sql server 2000 compatibility.I really appreciate all the help I can get on this..

Grant select, exec permission to SP, inline, scalar & table-values functions

Posted: 26 Apr 2013 06:12 AM PDT

I need to grant a user to select & exec permissions to SP, inline, scalar & table-values functions....but I need this done in every databases. There are 50 databases on this instance.Anyone have a script to accomplish this? Please help. Thanks.SueTons.

Convert SQL To Access (Generation of random values at time intervals)

Posted: 26 Apr 2013 06:44 AM PDT

I'm hoping someone can help me with my delema. I've posted it in detail here[url]http://stackoverflow.com/questions/16243905/convert-sql-to-access-generation-of-random-values-at-time-intervals[/url]Basically, My goal is to create a make-shift model that will never run out of data because time is auto incremented with a random value. I did this in SQL but now I need to do it in Access and I have basically no experience. Any help even just reccomending certain articles or sites is very much appreciated. Thanks

Unique Constraint Across More Than One Column

Posted: 26 Apr 2013 05:47 AM PDT

Hi,I have a table that contains, among other columns, 4 columns that contain the same type of data, call them Chip1, Chip2, Chip3, Chip4. I want to create an Index that will check that the same entry cannot appear more than once in any row of any of the columns.So, if Chip1 = ABC then ABC can only appear once in Chip1 and not at all in Chip2, 3 or 4. It would be better to do this as a one-to-many to another table but unfortunately the structure exists already. Is there a way of setting up a constraint that will prevent duplicates?Thanks

Suspended Commands on master db

Posted: 30 Sep 2012 04:23 PM PDT

HiI'm hoping someone will be able to cast some light on my current server issue.There are a number of commands which on the master db which have a suspended status, with significant wait times along with them.Command........................Wait Time...........Wait TypeSIGNAL HANDLER..............269275190..........KSOURCE_WAKEUPTASK MANAGER................269282488..........ONDEMAND_TASK_QUEUEBRKR EVENT HNDLR...........269276124..........BROKER_EVENTHANDLERBRKR TASK......................269282100..........BROKER_TRANSMITTERBRKR TASK......................269282095..........BROKER_TRANSMITTERFT GATHERER...................470649..............FT_IFTS_SCHEDULER_IDLE_WAIT(Apologies for my crude table)None of these have a Blocked By SPID listed against them. If my calculations are correct, the longer suspended tasks were all put into this state around 72 hours ago - in my part of the world that means Friday evening at around 6pm. This points the finger at one or a combination of scheduled jobs involved in processing XML data rerieved from an external webservice. Unfortunately the logs that far back have now been purged - cause for me to reconsider our clean up regime.From my research so far I get it that these are system tasks and as such they cannot be killed. I also understand that the BRKR tasks are created by the Service Broker and probably relate to our use of DB Mail or some other background operation.I'm seeking to understand what may have given rise to these and why. Later this evening I will restart the server, expecting these tasks to clear during that process. The need to uderstand what is going on is driven by wanting to avoid them in the future as I suspect that they have played a role in very poor performance from the server today.I look forward to someone perhaps being in a position to provide some possible explanation of this situation. My thanks in advance.CheersRowan

How to delete the duplicate row without any unique value? please help

Posted: 26 Apr 2013 02:40 AM PDT

I have a table of contacts that has no unique key on it. The users have entered multiple copies of several people's information and I want to remove the duplicate values.Here are the column namesLast_Name, First_NAme, Department, Email, phone, Sid (sid can be null)Please help-

Backups Failing

Posted: 26 Apr 2013 01:28 AM PDT

Hi, In my production environment there are only two drives C: and D: drives. The backups has to go the mapped drive named Z: The backups are failing now.I went to backup maintenance plans history and found this message Error msg: Could not find a part of the path 'z:\\xxx_TransactionLog_20130426091520.txt'.can any one help me whats going on here.

SQLPS vs SSMS

Posted: 26 Apr 2013 02:58 AM PDT

Ran into a SNAFU. I have a simple script that will "create" creation scripts for any object in an object folder. (get-childitem | %{$_.Script()} > C:\temp\whatever.sql)Let's use the example I want to script all my JOBS to be recreated on another server. It should be you run this script, load the "whatever" on another server and "there ya go'. But, right after the first job is created the sql failures begin. I looked a little closer and found the script generation leaves out the GO command that should be there just prior to the next BEGIN TRANSACTION. No problem, I use WORD and a little Find/Replace magic and we're good to go. (BTW check out ^c in the Replace box)If you open the Detailed Obj Expl in SSMS and highlight all the jobs, you can right click and get the same script except the GO is there. Since Microsoft uses PowerShell under the covers I never expected this result. Did I miss something or is this a no go plan?I guess I could extend the script to put the GO in , but REALLY...

wich OS is better for slq server 2008 R2

Posted: 26 Apr 2013 12:13 AM PDT

Iam creating a new windows server in the cloud (Dediserve), this will be a database server and I should use SQL SERVER 2008 R2 standard edition, my question is: what OS I should use to a better sql server performance?windows 2008 r2 or windows 2012, both standard eddition.Thanks

Which one is better?

Posted: 25 Apr 2013 10:19 PM PDT

Here is sample code below:Both queries will retun same result.But I want to know which one better to use? CREATE TABLE #temp1 (ID int, Name varchar(10))INSERT INTO #temp1 VALUES (1,'A'),(2,'B'),(3,'C')CREATE TABLE #temp2 (ID int, Name varchar(10))INSERT INTO #temp2 VALUES (1,'A'),(2,'B'),(4,'D')SELECT t.ID, t.Name FROM #temp1 tLEFT JOIN #temp2 t1 ON t.ID = t1.ID WHERE t1.ID IS NULLSELECT t.ID, t.Name FROM #temp1 t EXCEPTSELECT t1.id, t1.name FROM #temp2 t1

Friday, April 26, 2013

[SQL Server] Selecting/Deleting rows with the same column information

[SQL Server] Selecting/Deleting rows with the same column information


Selecting/Deleting rows with the same column information

Posted: 26 Apr 2013 07:38 AM PDT

I need to delete some rows from our system that have the same transaction id based on an accounting date. Our primary key for the table is MtrNo, MtrSfx, TrnxID, RecCode. Here's some example data:ProdDate | AcctDate | MtrNo |MtrSfx | TrnxID | RecCode------------------------------------------------------2/1/2011 | 8/1/2011 | 365 |A | 8301 | RR2/1/2011 | 2/1/2013 | 365 |A | 8301 | RR2/1/2011 | 2/1/2011 | 365 |A | 8301 | OR3/1/2011 | 9/1/2011 | 365 |A | 8302 | RR3/1/2011 | 3/1/2013 | 365 |A | 8302 | RR3/1/2011 | 3/1/2011 | 365 |A | 8302 | ORI want to be able to delete all the most recent rows based on AcctDate that have an RR RecCode. So in the above table, I'd want to delete:2/1/2011 | 2/1/2013 | 365 |A | 8301 | RR3/1/2011 | 3/1/2013 | 365 |A | 8302 | RRIt seems to be simple but I'm not very good with T-SQL. I would assume I need a sub-query that uses max, group by, and count.Would something like the query below work?DELETE FROM TblWHERE (SELECT MtrNo, MtrSfx, TrnxID, RecCode, MAX(AcctDate)FROM TblWHERE RecCode = 'RR'GROUP BY MtrNo, MtrSfx, TrnxID, RecCodeHAVING COUNT(TrnxID) > 1)The select seems to give me the right results but I don't know how the delete statement works and if it would just delete the columns I bring back.Any help would be greatly appreciated!

Dynamic Pivot Table

Posted: 26 Apr 2013 05:37 AM PDT

[img]http://farm9.staticflickr.com/8546/8684300282_1697647437_o.png[/img]I'm trying to pivot the data so that all of the PostClickConversions are aggregated for each ActivityTagID (by Date & AdID) as a column so the result set will look like this:[img]http://farm9.staticflickr.com/8545/8683197697_c30fdbba0b_o.png[/img]My attempt:[quote] DECLARE @PivotColumnHeaders VARCHAR(MAX) SELECT @PivotColumnHeaders = COALESCE( @PivotColumnHeaders + ',[' + cast([ActivityTagID] as varchar) + ']', '[' + cast([ActivityTagID] as varchar)+ ']' )FROM dbo.ConversionsTest DECLARE @PivotTableSQL NVARCHAR(MAX) SET @PivotTableSQL = N' SELECT * FROM ( select [date],[AdId],[ActivityTagID],[PostClickConversions]from dbo.ConversionsTest ) AS PivotData PIVOT ( sum([PostClickConversions]) FOR [ActivityTagID] IN ( ' + @PivotColumnHeaders + ' ) ) AS PivotTable ' EXECUTE(@PivotTableSQL)[/quote]The error message yields:[quote]Msg 8156, Level 16, State 1, Line 14The column '280378' was specified multiple times for 'PivotTable'.[/quote]HELP!!:w00t:

How to merge two sql select statement results I tried it but it not get please see it in detailed explination with my query

Posted: 25 Apr 2013 07:14 PM PDT

Hi All,My Query Goes Like This, Select TT.ID,TT.NAME,ROUND((CAST((Sum(TJA.MINS)) as FLOAT)/60),0) AS HOURS From MYTABLE1 as TT INNER JOIN MYTABLE2 as TB On TT.ID=TB.ID INNER JOIN MYTABLE3 as TH On TB.BID=TH.BID INNER JOIN MYTABLE4 as TJA On TJA.HID=TH.HID Where TJA.JID=41 group by TT.ID,TT.NAME UNION Select TJA.ID,TT.NAME,ROUND((CAST((Sum(TJA.MINS)) as FLOAT)/60),0) AS HOURS From MYTABLE1 as TT INNER JOIN MYTABLE2 as TJA On TT.ID=TJA.ID wHERE TJA.JID=41 group by TJA.ID,TT.NAMEThe First SQL Statement Result was like below one,ID NAME HOURS1 AAA 02 BBB 103 CCC 04 DDD 0The Second SQL Statement Result was like below one,ID NAME HOURS1 AAA 202 BBB 03 CCC 04 DDD 0After writing the The above UNION Statement i get like below one ID NAME HOURS1 AAA 01 AAA 202 BBB 02 BBB 103 CCC 04 DDD 0It was wrong I want to get result like below one ID NAME HOURS1 AAA 202 BBB 103 CCC 04 DDD 0Please give solution to me Thanks In Advance,VenkiDesai.

Problem with joining two select query statements.

Posted: 25 Apr 2013 05:00 PM PDT

Hi All,I Have Two Select Query Statement Result sets I want to combine those two sets.The Below One Is my [b]first query resultant set[/b],ID NAME HOURS1 AAA 02 BBB 103 CCC 04 DDD 0The Below One Is my [b]Second query resultant set[/b],ID NAME HOURS1 AAA 202 BBB 03 CCC 04 DDD 0After Joining two results i.e., My First Query & Second Query i want to get like below one,ID NAME HOURS1 AAA 202 BBB 103 CCC 04 DDD 0But i am not getting the result.After Joining two results i am getting the final one like below but it was wrongID NAME HOURS1 AAA 01 AAA 202 BBB 02 BBB 103 CCC 04 DDD 0For the Joining two select queries am using Below Query Select TT.ID,TT.NAME,ROUND((CAST((Sum(TJA.MINS)) as FLOAT)/60),0) AS HOURS From MYTABLE1 as TT INNER JOIN MYTABLE2 as TB On TT.ID=TB.ID INNER JOIN MYTABLE3 as TH On TB.BID=TH.BID INNER JOIN MYTABLE4 as TJA On TJA.HID=TH.HID Where TJA.JID=41 group by TT.ID,TT.NAME UNION Select TJA.ID,TT.NAME,ROUND((CAST((Sum(TJA.MINS)) as FLOAT)/60),0) AS HOURS From MYTABLE1 as TT INNER JOIN MYTABLE2 as TJA On TT.ID=TJA.ID wHERE TJA.JID=41 group by TJA.ID,TT.NAMEPlease give the solution for me.Thanks In Advance,Venki Desai.

Search This Blog