Quantcast
Channel: SQLServerCentral » SQL Server 2008 » SQL Server 2008 - General » Latest topics
Viewing all 16406 articles
Browse latest View live

Get Table Data - Historical Table

$
0
0
I've the following table: [code="vb"]department - student - start_date - end_date 1 102 2016-01-01 2016-01-03 1 102 2016-01-04 2016-01-07 1 102 2016-01-08 2016-01-11 1 102 2016-01-12 2016-01-14 1 104 2016-01-15 2016-01-17 1 104 2016-01-18 2016-01-20[/code] My expected output would be as follows:[code="vb"]department - student - start_date - end_date 1 102 2016-01-01 2016-01-14 1 104 2016-01-15 2016-01-20 [/code] I've tried to use min/max in the select query using group by. But it didn't work. Any idea to do the above?

Sum Time in Sql

$
0
0
I am trying to sum up time and almost did it. Now I would like to sum up top 2 time as follows:[code="vb"]SELECT TOP 2*, ISNULL((RIGHT('00' + CONVERT(VARCHAR(10), SUM(DATEDIFF(MINUTE, FromTime, ToTime)) / 60), 2) + ':' + RIGHT('00' + CONVERT(VARCHAR(2), SUM(DATEDIFF(Minute, FromTime, ToTime)) % 60), 2) + ':' + RIGHT('00' + CONVERT(VARCHAR(2), SUM(DATEDIFF(SECOND, FromTime, ToTime)) % 60), 2)), 0) AS TotalTime FROM Demo GROUP BY ID, FromTime, ToTime[/code]The output is as follows:[img]https://s17.postimg.io/s0wxtvlbz/img.png[/img]So is there any way or still possible to add the sum of the TotalTime column at the end? I would appreciate if any idea is shared. Thanks.

Ensuring logins are not used

$
0
0
There are approximately 30 logins on one of our PROD instances of SQL Server that I believe are unused. Here is what I have checked so far:1) Audited failed and successful logins for 1 month2) Used RedGate SQL Search to ensure the logins aren't hard-coded into any DB objectsIs there anything else I should check to see if a login is being used? Thanks!

How to use One to many relation with sub-query

$
0
0
I have created below query for SSRS with one to many relation join.Basically my logic is =>First check the inc_id in incident table reference to the usr_id =>Retrieve the data from actions table related to usr_id in incident tablePlease help me out to get the result as sample like below,Table:incident+--------+-------------+--------+---------+| inc_id | date_logged | usr_id | dept_id |+--------+-------------+--------+---------+| 100 | 1-Aug-15 | 1 | 10 || 101 | 1-Sep-15 | 2 | 20 || 102 | 25-Aug-15 | 1 | 10 |+--------+-------------+--------+---------+Table:Actions+--------+-----------+----------+--------------+--------+---------+| inc_id | date_act | act_type | servicr_time | usr_id | dept_id |+--------+-----------+----------+--------------+--------+---------+| 100 | 2-Aug-15 | Travel | 300 | 1 | 10 || 100 | 3-Aug-15 | Remote | 200 | 3 | 30 || 100 | 5-Aug-15 | Travel | 200 | 1 | 10 || 100 | 10-Sep-15 | Travel | 250 | 1 | 10 || 101 | 1-Sep-15 | Travel | 150 | 2 | 20 || 101 | 1-Sep-16 | Travel | 120 | 3 | 30 || 102 | 29-Aug-15 | Travel | 150 | 1 | 10 || 102 | 30-Aug-15 | Remote | 120 | 1 | 10 |+--------+-----------+----------+--------------+--------+---------+[b]My Query:[/b]SELECT COUNT(distinct inc.inc_id) AS [inc_count], inc.inc_id, inc.dept_id, inc.usr_id, DATEPART(YEAR, a.date_act) 'act_year', DATENAME(MONTH, a.date_act) 'act_month', ( SELECT ISNULL(SUM(ac.service_time), 0) AS Expr1 FROM actions as ac WHERE (ac.act_type IN ('Travel Time')) AND (ac.inc_id = inc.inc_id) AND (DATEPART(YEAR, ac.date_act) = DATEPART(YEAR, a.date_act)) AND (DATENAME(MONTH, ac.date_act) = DATENAME(MONTH, a.date_act)) AND ac.date_act BETWEEN '2015-08-01' AND DATEADD(day, 1, '2015-09-30') ) / 60 AS [Travel_Time], ( SELECT ISNULL(SUM(ac.service_time), 0) AS Expr1 FROM actions as ac WHERE (ac.act_type IN ('Remote')) AND (ac.inc_id = inc.inc_id) AND (DATEPART(YEAR, ac.date_act) = DATEPART(YEAR, a.date_act)) AND (DATENAME(MONTH, ac.date_act) = DATENAME(MONTH, a.date_act)) AND ac.date_act BETWEEN '2015-08-01' AND DATEADD(day, 1, '2015-09-30') ) / 60 AS [Remote_Time]FROM incident AS inc INNER JOIN inc_data as id ON inc.inc_id = id.inc_id INNER JOIN actions as a ON a.inc_id = inc.inc_id WHERE a.dept_id IN (10) AND a.date_act BETWEEN '2015-08-01' AND DATEADD(day, 1, '2015-09-30')GROUP BY inc.inc_id,a.date_act,inc.dept_id, inc.usr_id[b]Expected Result Table:[/b]+-----------+--------+------+-----------+--------+---------+-------------+-------------+| inc_count | inc_id | Year | Month | usr_id | dept_id | Travel_Time | Remote_Time |+-----------+--------+------+-----------+--------+---------+-------------+-------------+| 1 | 100 | 2015 | August | 1 | 10 | 500 | 0 || 1 | 100 | 2015 | September | 1 | 10 | 250 | 0 || 1 | 102 | 2015 | August | 1 | 10 | 150 | 120 |+-----------+--------+------+-----------+--------+---------+-------------+-------------+

Blocked Process Alert issues

$
0
0
This is really beginning to annoy me.I have Blocked Process Alerts on every single server in our environment. The alerts are set to email us when the blocked processes get above 2. So what happens? Our DEV server (not Production, not any of the others) is constantly sending emails out about the blocked processes. I finally got annoyed and set up a job to try and catch the blocked processes (runs every 3 minutes). The problem is, the job isn't catching the events that trigger the alerts. In fact, it's catching other blocking events that don't trigger the alerts. I'm about at my wits end.Does anyone have any suggestions on code that can assist me with catching whatever is causing the alerts?The code I'm using I got from Ian Stirk's website / blog. It's attached for reference if you want to see it.

Unable to open Alerts in SQL Server Agent / Cannot view properties

$
0
0
I am unable to open Alerts in SQL Server Agent and Cannot view the properties using GUI. Although I am able to create and modify alerts via ScriptIt gives me this exception. Anybody has any idea ?===================================Cannot show requested dialog.===================================Cannot show requested dialog. (SqlMgmt)------------------------------Program Location: at Microsoft.SqlServer.Management.SqlMgmt.DefaultLaunchFormHostedControlAllocator.AllocateDialog(XmlDocument initializationXml, IServiceProvider dialogServiceProvider, CDataContainer dc) at Microsoft.SqlServer.Management.SqlMgmt.DefaultLaunchFormHostedControlAllocator.Microsoft.SqlServer.Management.SqlMgmt.ILaunchFormHostedControlAllocator.CreateDialog(XmlDocument initializationXml, IServiceProvider dialogServiceProvider) at Microsoft.SqlServer.Management.SqlMgmt.LaunchForm.InitializeForm(XmlDocument doc, IServiceProvider provider, ISqlControlCollection control) at Microsoft.SqlServer.Management.SqlMgmt.LaunchForm..ctor(XmlDocument doc, IServiceProvider provider) at Microsoft.SqlServer.Management.UI.VSIntegration.ObjectExplorer.ToolMenuItemHelper.OnCreateAndShowForm(IServiceProvider sp, XmlDocument doc) at Microsoft.SqlServer.Management.SqlMgmt.RunningFormsTable.RunningFormsTableImpl.ThreadStarter.StartThread()===================================Failed to create/initialize Agent Alert dialog. (SqlManagerUI)------------------------------Program Location: at Microsoft.SqlServer.Management.SqlManagerUI.AgentAlert..ctor(CDataContainer dataContainer)===================================Cannot create/initialize Response page. (SqlManagerUI)------------------------------Program Location: at Microsoft.SqlServer.Management.SqlManagerUI.AgentAlert.AddResponsePage() at Microsoft.SqlServer.Management.SqlManagerUI.AgentAlert..ctor(CDataContainer dataContainer)===================================Object reference not set to an instance of an object. (SqlManagerUI)------------------------------Program Location: at Microsoft.SqlServer.Management.SqlManagerUI.AgentAlertResponse.RefreshJobComboBoxAndSelectJob(Job currentJob) at Microsoft.SqlServer.Management.SqlManagerUI.AgentAlertResponse.RefreshJobComboBox() at Microsoft.SqlServer.Management.SqlManagerUI.AgentAlertResponse..ctor(CDataContainer dataContainer, String agentAlertName) at Microsoft.SqlServer.Management.SqlManagerUI.AgentAlert.AddResponsePage()

Load flat file error code -1071607689

$
0
0
Hi, I have a SQL Server 2008 in Server 1 , where I have a job of loading flat file in Table.the flat file which is a zip is located in server 2 the SSIS package unzip, check if the header contains all fields then load it in database table.I noticed that the load is not complete, when I open my logfile I found errorcode = -1071607689 and errorcolumn = 883 , the rejected lines are dates for example 31-Oct-1613-May-05but it accepts for example31-SEP-13I have to open file to change date to german and to run the job ... it's weired, I tried to force my languages to english in my 2 servers but no luck...I googled and I found the description of the error code : The data value cannot be converted for reasons other than sign mismatch or data overflow.but I can't understand this messageplease Help.

sp_monitor

$
0
0
HiCan you please suggest in which situation does it make sense to run:[code="sql"]USE [user_db/anydb]EXEC sp_monitor [/code]What is my benefit of using such internal SP?

SQL Connections Not Reported

$
0
0
Hello,I know this topic is covered all over the Internet, however, I am unable to find a post that explains the behavior that I am seeing in a manner I understand. I've read quite a bit about connection pooling and I am confused at this point so I will explin what I am seeing. Mind you that this is from a Systems perspective.NETSTAT -AN results in 700 connections in an [u]ESTABLISHED[/u] state from the SQL Server to itself on port 1433.The following returns 300 less connectionsSELECT COUNT(dbid) as TotalConnectionsFROM sys.sysprocessesWHERE dbid > 0 I've tried many other means that people have posted for getting a connection count and the results remain the same. I have looked as sp_whoisactive to include sleeping spids, sp_who, sp_who2 and summing up the results and they line up with the SQL query above.I've looked at process explorer and the connections tab of the properties for processes that are connected and using SQL. I see no smoking gun.I've looked at .NET performance counters and can see some minute connection pool activity. I've turned on the ODBC counters and see no activity for connection pools.So, I am struggling to understand why I have 300 missing connections that appear as ESTABLISHED in the netstat output.Has anyone encountered this scenario that would be willing to share a proven troubleshooting routine that would expose what has these connections open or prove why they are open?#EDIT# Since 10 people have looked at this and no suggestions I will pose yet another related question. As this server is a VM and I have seen what I believe is an issue with VEEAM causing access to SQL halt when the backup snapshot is removed, is there any chance that SQL wouldn't show the connections but netstat would still think that they are established? I didn't think that it was possible but I'm scratching my head on this one. In the Windows event log I see some NTFS event ID 57 messages at the same time that the sql logs I show a series of these events for each database.I/O is frozen on database X. No user action is required. However, if I/O is not resumed promptly, you could cancel the backup.I/O was resumed on database X. No user action is required.Database backed up. Database X, creation date.....I assume that this can't be the case as the events all happen sub second and the backup completes. Thus I doubt that existing connections are getting orphaned if you will if there is even such a thing. Beyond this the server looks as healthy as one can get.

Length specified in network packet payload did not match number of bytes read

$
0
0
Length specified in network packet payload did not match number of bytes read; the connection has been closed. Please contact the vendor of the client library. [CLIENT: xxx.xx.xxx.xx]Client IP address is same as the server its producing the error on. I get these messages around 12pm everyday. Can someone please help me.

SSIS Script Reference Missing

$
0
0
I cannot permanently add the assembly Microsoft.Office.Interop.Excel into a SSIS script. While in the script editor it works just fine, but if I exit the script editor then go back into it the reference is gone.I have searched online and found others who have similar problems, e.g. https://social.msdn.microsoft.com/Forums/sqlserver/en-US/9a6b1867-b787-4f4d-9a57-abf651b2292c/referencing-microsoftofficeinteropexceldll?forum=sqlintegrationservices However I cannot get any suggested solution to work.I can see the assembly is included in the C:\Windows\assembly folder. I am using SQL Server 2008 R2 on a 64 bit computer. The BIDS version is 9.0.30729.4462.If I add the reference with the script editor open, then in the Project Explorer window under References I have the following 3 Microsoft references:- Microsoft.Office.Interop.Excel- Microsoft.SqlServer.ManagedDTS- Microsoft.SqlServer.ScriptTaskWhen I close the editor and reopen it the first reference is gone but the other two remain.Can someone please tell me how I can add the reference permanently?

Identity column versus RowID

$
0
0
Hi there, I have a table with 100 million records containing Employee information without a Unique key.[code="sql"]Create Table Employee(EmpName varchar(100),EmpAddress1 varchar(max),EmpAddress2 varchar(1000),EmpAddress2 varchar(500),EmpCity varchar(100),EmpState varchar(50),StartDate Datetime,EndDate Datetime)[/code]I wanted to create a full text search and hence needed to create a unique key.I thought of 2 different ways of doing it.1A. [code="sql"]ALTER TABLE EMPLOYEE ADD RowID [int] NULL[/code]1B. [code="sql"]DECLARE @id INT SET @id = 0 UPDATE [MYDB].[dbo].[Employee] SET @id = RowID = @id + 1 OPTION ( MAXDOP 1 )[/code]1C: [code="sql"]ALTER TABLE [dbo].[Employee] ALTER COLUMN RowID [int] NOT NULL GO[/code]1D: [code="sql"]CREATE UNIQUE NONCLUSTERED INDEX [uixEmp-RowID] ON [dbo].[Employee] (RowID) GO[/code]OR [code="sql"]Create Table Employee_2(ID int identity(1,1) not null,EmpName varchar(100);EmpAddress1 varchar(max);EmpAddress2 varchar(1000);EmpAddress2 varchar(500);EmpCity varchar(100);EmpState varchar(50);StartDate Datetime,EndDate Datetime)INSERT INTO Employee_2(EmpName,EmpAddress1,EmpAddress2,EmpAddress2 ,EmpCity,EmpState,StartDate,EndDate)SELECT EmpName,EmpAddress1,EmpAddress2,EmpAddress2 ,EmpCity,EmpState,StartDate,EndDate FROM dbo.Employee[/code]I am not sure which one is better.Any help is appreciated.ThanksMR

Queries and joins with different locations.

$
0
0
I am trying to set up a query that will report on quantities ordered, shipped and backordered (those that didn't ship).The issue is that I am ordering from one location and may be able to ship from that location, sometimes from another location and sometime the original location and another.The part that is difficult is when I order from an original location and ship part of the order from another. Even though I shipped only from one location I need to show both locations.If I have the following schema and data:[code]IF OBJECT_ID('tempdb..#Order') IS NOT NULL DROP TABLE #OrderIF OBJECT_ID('tempdb..#Product') IS NOT NULL DROP TABLE #ProductCREATE TABLE #Order( OrderNumber VARCHAR(10) , Location VARCHAR(20) , Total INT)CREATE TABLE #Product( OrderNumber VARCHAR(10) , Product VARCHAR(20) , Location VARCHAR(20) , Quantity INT)INSERT #OrderVALUES ( '001', 'Dallas', 10 )INSERT #ProductVALUES ( '001', 'WidgetA', 'Dallas', 3 ) INSERT #OrderVALUES ( '002', 'Dallas', 20 )INSERT #ProductVALUES ( '002', 'WidgetB', 'Hampton', 8 ) INSERT #OrderVALUES ( '003', 'Dallas', 15 )INSERT #ProductVALUES ( '003', 'WidgetC', 'Dallas', 3 )INSERT #ProductVALUES ( '003', 'WidgetC', 'Hampton', 7 )[/code]I want to end up with the following result:[code]Order# Product Location Qty Ordered Qty Shipped Qty Backordered001 WidgetA Dallas 10 3 7002 WidgetB Dallas 20 0 12002 WidgetB Hampton 8 8 0003 WidgetC Dallas 15 3 5003 WidgetC Hampton 7 7 0[/code]So for 001, we have ordered for Dallas and shipped 3 from Dallas, so they all show on one line.For 002, we have ordered for Dallas, but shipped from Hampton, so we have 2 lines (one for each location).For 003, we have ordered 15 for Dallas and shipped 3 from Dallas and 7 from Hampton. So we again have two rows.How would I set up the query to handle this.The problem is that joins don't seem to work by themselvesThanks,Tom

Comparing Data from two tables on two different servers

$
0
0
I have a HQ server and Office_location server. we have a replication application that moves new/updated data from HQ to Office and/or Office to HQ.We have noticed that we are missing some records from one or the other location also we are sometime seeing a record in both locations but one is not matching the other.Is there any FREE(CHeap) tools that i can do a data matching/validation.

Unsafe assembly

$
0
0
Hi all,Recently following message appears in SQL Error log.Any ideas?'Unsafe assembly 'microsoft.sqlserver.mpusqlclrwrapper, version=10.0.0.0, culture=neutral, publickeytoken=89845dcd8080cc91, processorarchitecture=msil' loaded into appdomain 271 (mssqlsystemresource.dbo[runtime].352)SQL Server 2008 R2Thank You advance

Need Trigger Script

$
0
0
Hi All,I need your help in creating a dynamic script to create after insert,update triggers on a given table.Trigger has to do following things:Trigger has to fire for every insert or update made on specified table and insert SQL INSERT statements like INSERT INTO TABLENAME(Columns ...) VALUES(...) queue_table(this table is common for all the tables), trigger should get columns from sys.columns and I need to create similar triggers for many tablesCreate table Test(Col1 int,Col2 nvarchar(500),Col3 bit,Col4 Datetime) CREATE TABLE queue_table ( queue_id BigINT NOT NULL IDENTITY(1,1) ,sql_stmt NVARCHAR(MAX) ,is_moved BIT DEFAULT(0) ,create_date datetime DEFAULT (Getdate()) )

Differences between sql server 2008 and 2008 R2

$
0
0
I did some research to find the differences between between sql server 2008 and 2008 R2 but couldnt find much. I know in R2, BI is made more effecient but is it different from what it is present in 2008? Can someone please explain me the major differences between sql server 2008 and 2008 R2. Thanks in advance.

SDLC

$
0
0
Hi all, Somewhat non-technical question, I'm going for a position where 'A good knowledge of the software development lifecycle as it pertains to SQL Server" is required.I'm guessing this is simply adding/altering of reports, SSIS packages and adding/fixing sprocs , but if anyone can point me to any recent and relevant articles or blogs, I'd be grateful.JB

FullText Index rank individual columns

$
0
0
Hi there, I have created a full text index on a table[code="sql"]CREATE TABLE temp.dbo.Students(StudentID int not null, Name varchar(100) not null, University nvarchar(max) null,Major varchar(200) null,Minor varchar(200) null, otherSkills varchar(500) null)[/code]I created Fulltext index on Major,Minor,Otherskills.I was able to search certain words like "Computer Science"[code="sql"]DECLARE @searchPhrase [nvarchar](100) = 'Computer Science' SET @searchPhrase = '"*' + @searchPhrase + '*"'SELECT StudentID FROM temp.dbo.Students WHERE CONTAINS((Major,Minor,Otherskills), @searchPhrase) [/code]Now, I want to rank these i.e. if searchPhrase is found in column 'Major' then Rank=100 if searchPhrase is found in column 'Minor' then Rank=50 if searchPhrase is found in column 'OtherSkills' then Rank=25 How can I do it?ThanksM

PERFORMANCE ISSUE ON SQL SERVER 2008

$
0
0
Good Day,I have a performance issue where I run a query/script on different SQL server versions, on the SQL Server 2012 this script runs for 2 secs, but on the 2008 Server version, it runs for 20 secs. i have used index scan and , all tables in the 2012 version and 2008 version, have the same indexes, what can i do to check and also improve the performance and also decrease the run-time to less than 5 secs as it is on the 2012 version.Please assist. Thankssee script belowDECLARE @flexOrderDefault INT = 1DECLARE @rnetOrderDefault INT = 2DECLARE @flexCpOrderDefault INT = 3DECLARE @flex9CpOrderDefault INT = 5DECLARE @cumulusPush INT = 1DECLARE @marketronPush INT = 3DECLARE @inventoryLogStatusUnverified INT = 0DECLARE @inventoryLogStatusScheduledInMarket INT = 1DECLARE @orderId INT = 0SELECT ooh.id Id,a.Name AdvertiserName,ag.name AgencyName,CONVERT(BIT, CASE ooh.countCumulus WHEN 0 THEN 0 ELSE 1 END) hasSpotsForCumulus, CONVERT(BIT, CASE ooh.countMarketron WHEN 0 THEN 0 ELSE 1 END) hasSpotsForMarketronFROM( SELECT ioh.id, SUM(CASE ioh.DispatchMethodID WHEN @cumulusPush THEN 1 ELSE 0 END) countCumulus, SUM(CASE ioh.DispatchMethodID WHEN @marketronPush THEN 1 ELSE 0 END) countMarketron FROM ( SELECT oh.id, acd.DispatchMethodID from Inventory i JOIN InventoryOrderSpot ios ON ios.InventoryID = i.ID JOIN OrderSpot os ON ios.OrderSpotID = os.ID JOIN OrderDetailWeek odw on odw.ID = os.OrderDetailWeekID JOIN OrderDetail od ON od.ID = odw.OrderDetailID JOIN OrderHeader oh ON oh.ID = od.OrderHeaderID JOIN ContractDetail acd ON acd.ID = i.ContractDetailID JOIN Station AS s ON s.id = acd.stationid JOIN Package as p on od.PackageID = p.ID JOIN PackageVehicle as pv on p.ID = pv.PackageID JOIN Vehicle V ON oh.ID = v.OrderHeaderID AND V.id = pv.VehicleID WHERE (oh.CumulusOrderDefaultID = @flexOrderDefault OR oh.CumulusOrderDefaultID = @rnetOrderDefault OR oh.CumulusOrderDefaultID = @flexCpOrderDefault OR oh.CumulusOrderDefaultID = @flex9CpOrderDefault) AND (ios.Status = @inventoryLogStatusUnverified OR ios.Status = @inventoryLogStatusScheduledInMarket) AND (@orderId = 0 OR oh.ID = @orderId) AND acd.DispatchMethodID = 1 ) ioh GROUP BY ioh.ID) oohjoin OrderHeader oh on ooh.id = oh.idJOIN Company a ON oh.AdvertiserID = a.IDJOIN Company ag ON oh.AgencyID = ag.IDORDER BY a.Name
Viewing all 16406 articles
Browse latest View live