Thursday, July 11, 2013

[SQL Server] Query by current month

[SQL Server] Query by current month


Query by current month

Posted: 11 Jul 2013 07:58 AM PDT

I am rather new to working with databases and queries. That being said.....I am trying to pull data in from an Oracle data base into an excel spread sheet. I already have the connections and everything, but I cant seem to figure out how to restrict the data to only that in the current month. I know i need to add a "where" clause to my query, but I cant find the proper one to insert. can someone help me out with this? the field that this is bassed off of is a date time field.

INSERTING PROBLEM

Posted: 10 Jul 2013 04:11 PM PDT

CREATE TABLE MYTABLE( NAME NVARCHAR(MAX), ID INT)INSERT INTO MYTABLE(NAME,ID) VALUES('AAA',1)INSERT INTO MYTABLE(NAME,ID) VALUES('AAA',2)INSERT INTO MYTABLE(NAME,ID) VALUES('AAA',3)so the output is,NAME IDAAA 1AAA 2AAA 3in front end i am having checkbox listin that i selected 3 items then the values will come like this '4,5,6'after getting those selected value items i want to insert it into databasefor example,NAME='BBB'IDs='4,5,6'so my requirement is if i send these above values to MYTABLE in databasethen the expected output looks likeNAME IDBBB 4BBB 5BBB 6please help me ,your help will be appreciableThanks in advance,Venkatesh Desai.k

how to add output parameter to existing sproc

Posted: 11 Jul 2013 01:41 AM PDT

I have been given a sproc which needs to have an output parameter added.It is the the line @UpdBearingStatusComplete INT OUT.when I type the name it has red squiggles under it and syntax check gives the error listed below.What am I doing wrong?ALTER PROCEDURE [dbo].[UpdBearingStatus] @BearingEtching VARCHAR(40), @BearingStatusHMIText Varchar(40)=NULL, @SpallSizeHMIText VARCHAR(40)=NULL, @TestSetID INT = 0, @Username VARCHAR(80)='SYSTEM', @ManualUpdateReason VARCHAR(255)=NULL--trying to add this line @UpdBearingStatusComplete INT OUT ASBEGINDECLARE @BearingID INT=0DECLARE @BearingStatusTypeIDNew INTDECLARE @SpallSizeTypeIDNew INTDECLARE @BearingStatusTypeIDPrev INTDECLARE @SpallSizeTypeIDPrev INTfrom CheckMsg 102, Level 15, State 1, Procedure UpdBearingStatus, Line 18Incorrect syntax near '@UpdBearingStatusComplete'.

Conversion failed due to datatype.

Posted: 11 Jul 2013 01:16 AM PDT

Hi,I am trying to generate ids as"Compidentity" as varchar .If the record is inserted with productcode- " Health"Column with value H1 shoul be added .If the record is inserted with " Dental "Column with Value D2 should be added.Here is what I have :( ProductCode Varchar(20), Compidentity int identity(1,1),status as casewhen productcode = 'Health'then 'H'+ cast(compidentity as varchar(20)) when productcode = 'Dental'then 'D' + cast(compidentity as varchar(20))else1end)Executes fine.But when I write an insert statement gives an error :" Conversion failed when converting the varchar value 'H1' to data type int."Please advise.

Invoke Batch file from Remote machine

Posted: 10 Jul 2013 04:48 PM PDT

Hello,I have created a batch file to restart one of the SQL Server service and I would like to invoke it from a remote machine.Is it possible??If yes,how?I really appreciate all of you for attempting to help me out.

Migration of Maintenance Plans - Server to Server

Posted: 10 Jul 2013 06:58 PM PDT

Hi All,I have setup some Maintenance plans over time and now am looking at installing a replacement server.Is there an easy way to migrate the plans over ( edit after if required ) Thanks

[Articles] Hiring Guitarists

[Articles] Hiring Guitarists


Hiring Guitarists

Posted: 10 Jul 2013 11:00 PM PDT

Hiring senior people is hard, but Steve Jones stumbled upon an idea that compares hiring technology people to hiring a senior level technology expert.

[MS SQL Server] SQL Server Memory Usage

[MS SQL Server] SQL Server Memory Usage


SQL Server Memory Usage

Posted: 11 Jul 2013 02:02 AM PDT

I observed that in my Production Server (SQL Server 2005)PF Usage: 496 GBTotal RAM: 511 GBAvailable RAM: 8 GB Database Size: 1 TBSQL Server process (SQLSVRVR.EXE) MEMORY USAGE in Task Manager: 493 GBist it normal ? or we need to take any action. Can you please any one suggest me ?

Piecemeal restore takes forever

Posted: 10 Jul 2013 10:42 PM PDT

Hi EveryoneI have a 1.1TB database with 700GB of data on a SQL Server 2008 R2 SP1 instance. Most data is row compressed and in 2 partitioned tables. A full backup is taken daily to 4 files on a NAS as part of the daily maintenance routine (which also includes index fragmentation, updating statistics and an integrity check directly before the full backup and in that order). The backup is also compressed.On a testserver I want to do a piecemeal restore, starting with the primary filegroup (the partitioned tables are in other filegroups). The primary filegroup file is 9GB and has about 3GB of data. The transaction logfile is 16GB. I know, with a restore, the transaction logfile is being zeroed which could take some time. On the other hand, the empty space in the primary data file is not being zeroed during a restore operation when Instant File Initialization is enabled. This is the case on my testserver. The problem is that the piecemeal restore takes a very long time, about 6 hours. I investigated and tried a few things to speed up the restore. Here they are:- Check if Instant File Initialization is enabled, it is.- Checking the performance of the whole chain (NAS, network, SAN), by restoring another backup with approximately the same size (3GB) from the same NAS to the same testserver over the same network. The restore was done in 2-4 minutes.- Checking the number of virtual logfiles, which is 41 and thus ok.- Take a partial backup and restore that one partially. This restore took 2-4 minutes. My conclusion: creating the mdf and ldf files is not the problem.- Altered the daily maintenance routine by adding a transactionlog backup after the integrity check and before the full backup, hoping that the transactions from the transactionlog caused by the earlier operations, are left out from the full backup. I'm not sure this makes sense, but to my understanding when SQL Server takes a backup, the transactions in the transaction log are also included for the redo/undo fase when restoring a the backup. Also, I opened the Performance Monitor to see disk activity during the restore operation. There is only disk activity during the beginning of the restore operation. Furthermore, when I execute sp_WhoIsActive during the restore operation, I see that the restore session is suspended (wait_info: BACKUPTHREAD) while network traffic stays at maximum. The CPU's are also processing 'something'. I'm beginning to suspect the restore operation is scanning every page in the full backup files somehow. Is there someone who knows if this is true or, if not, knows the true reason why the piecemeal restore is so slow?Thanks

Frozen process

Posted: 10 Jul 2013 04:56 PM PDT

Hi,I have a process in "killed/rollback" state for a long time. I found two workarounds for this:1. Restart the SQL instance2. If the process that is running is external to SQL server i.e. OSQL, sqlmaint, and if you do the KILL SPID on it, it might not finish the rollback.To avoid the server restart of the SQL Service, do not run the KILL SPID within the SQL Server instead kill the process at the OS level and the SPID from within the SQL will disappear.The fist solution is an easy one, but not desirable. The second is tricky to find out.By running this query:DECLARE @v1 VARBINARY(64)SELECT @v1 = sql_handle FROM sys.dm_exec_requests WHERE session_id = 110SELECT * FROM sys.dm_exec_sql_text(@v1)I found that the process was executing this command:DROP DATABASE MyDBName_dbss -- this is a database snapshotAt the time when I looked the snapshot did not exist.Does SQL Server run something external when dropping database snapshots? If so, how can I determine the process at the OS level?Or may be, how can I change the dropping of the snapshots, so I don't end up in a situation like this?Thanks.

Memory Issues on production sql server

Posted: 10 Jul 2013 07:21 AM PDT

Please help me in this situation.Total memory on box : 10 GBSingle node, non clustered production boxMin memory is set to 0Max Memory is set to 8 GBFrom last month the box Memory is constantly at 95%CPU usage is very lowhere is the screen shot from the task manager[img]http://img838.imageshack.us/img838/1104/p77j.png[/img]How to find Is SQL server using the complete 8GB ?Management is asking to reduce the SQL server memory setting to 7GBIs this fine to decrease the memory limit. Please advice.

Error uploading Files

Posted: 10 Jul 2013 09:08 AM PDT

One of user is complaining about a reporting server issue, whenever they try to upload a file, they are getting the below error....i checked for space issue......it's not the space issue, i am kind of lost as to what to check next. Please see the error message below and advise if you have any idea. Client found response content type of 'text/html; charset=utf-8', but expected 'text/xml'. The request failed with the error message: -- <html> <head> <title> SQL Server Reporting Services </title><meta name="Generator" content="Microsoft SQL Server Reporting Services 9.00.5069.00" /> <meta name="HTTP Status" content="500" /> <meta name="ProductLocaleID" content="9" /> <meta name="CountryLocaleID" content="1033" /> <style> BODY {FONT-FAMILY:Verdana; FONT-WEIGHT:normal; FONT-SIZE: 8pt; COLOR:black} H1 {FONT-FAMILY:Verdana; FONT-WEIGHT:700; FONT-SIZE:15pt} LI {FONT-FAMILY:Verdana; FONT-WEIGHT:normal; FONT-SIZE:8pt; DISPLAY:inline} .ProductInfo {FONT-FAMILY:Verdana; FONT-WEIGHT:bold; FONT-SIZE: 8pt; COLOR:gray} A:link {FONT-SIZE: 8pt; FONT-FAMILY:Verdana; COLOR:#3366CC; TEXT-DECORATION:none} A:hover {FONT-SIZE: 8pt; FONT-FAMILY:Verdana; COLOR:#FF3300; TEXT-DECORATION:underline} A:visited {FONT-SIZE: 8pt; FONT-FAMILY:Verdana; COLOR:#3366CC; TEXT-DECORATION:none} A:visited:hover {FONT-SIZE: 8pt; FONT-FAMILY:Verdana; color:#FF3300; TEXT-DECORATION:underline} </style> </head><body bgcolor="white"> <h1> Reporting Services Error<hr width="100%" size="1" color="silver" /> </h1><ul> <li>An internal error occurred on the report server. See the error log for more details. (rsInternalError) <a href="http://go.microsoft.com/fwlink/?LinkId=20476&EvtSrc=Microsoft.ReportingServices.Diagnostics.Utilities.ErrorStrings&EvtID=rsInternalError&ProdName=Microsoft%20SQL%20Server%20Reporting%20Services&ProdVer=9.00.5069.00" target="_blank">Get Online Help</a></li><ul> <li>For more information about this error navigate to the report server on the local server machine, or enable remote errors</li> </ul><hr width="100%" size="1" color="silver" /><span class="ProductInfo">SQL Server Reporting Services</span> </ul> </body> --.Thanks,SueTons.

[SQL 2012] In 2012, how to create a fully contained database?

[SQL 2012] In 2012, how to create a fully contained database?


In 2012, how to create a fully contained database?

Posted: 11 Jul 2013 12:21 AM PDT

based on a previous post here, someone had a quesiton on Contained databases, so i decided to create one myself to follow along.BOL says the settings for the database containment can be NONE, PARTIAL or FULL.When you create a database via the GUI, you only get a selection for PARTIAL or NONE.so how do you create a fully contained database?[img]http://www.sqlcoffee.com/images/SQLServer2012_0009_0003.PNG[/img]if i use the scripting option, and try to modify the script to say FULL, i get a syntax error.[quote][color="#FF0000"]Msg 156, Level 15, State 1, Line 2Incorrect syntax near the keyword 'FULL'.Msg 911, Level 16, State 1, Line 1Database 'FullyContained' does not exist. Make sure that the name is entered correctly.[/color][/quote][code]CREATE DATABASE [FullyContained] CONTAINMENT = FULL ON PRIMARY ( NAME = N'FullyContained', FILENAME = N'F:\SQLData\SQL2012\FullyContained.mdf' , SIZE = 4096KB , FILEGROWTH = 1024KB )by the way, my Google-Fu is strong, and everything i see in BOL so far shows changing a database from None to Partial, but nothing for Partial to FULL or None to FULL LOG ON ( NAME = N'FullyContained_log', FILENAME = N'F:\SQLData\SQL2012\FullyContained_log.ldf' , SIZE = 1024KB , FILEGROWTH = 10%)[/code]

Moving data from Server-A/table-x to Server-B/Table-x

Posted: 11 Jul 2013 12:41 AM PDT

Dear All, I have a script that has 20-25 small single line queries.Objective of script is to select all data from Server-A/table-x and copy to Server-B/Table-x. Overall script takes almost 6-7 hours to complete as most of the tables have more then a billion records. Individual queries has nothing to optimize as they all are single liner select queries. What Should I do to reduce this time, or should I completely change the strategy.Any help will be highly appreciated.Thanks.

SQL Express Tools

Posted: 10 Jul 2013 08:47 PM PDT

Hi, sorry for the fairly basic question but I want to download SQL Express Tools, but just want the SSMS Tool, not Full Express and I'm having difficulty finding it. I already have a number of live production Express installations on various servers and just want to add the SSMS tool, therefore re-installing Express is not an option, i just want the tool! Thanks

Attunity CDC Service Between SQL2012 and Oracle

Posted: 10 Jul 2013 07:53 PM PDT

Hello everyone,I work the last days on a Project where I must transfer Data from an Oracle Database to a Sql Server 2012 Database. The CDC Service works fine and it captures all changes on the Source Database but the Data when transfered to the Destination DB, to our beloved SQL Server 2012, it is altered!!!See, the source Data on the Oracle DB = '164f3293-e5fa-435e-a15d-f67ab12b1486'and the Data on the Destination = '??????????????????' Why?Thank you a lot!Regards,Rena

Contained database

Posted: 10 Jul 2013 05:38 PM PDT

Hi,Can someone please explain what is the downside of switching a database into contained database?I know the benefit of contained database is easy for migrating between server/instance, it makes the database very portable.Any help will be much appreciated.Thanks

How to overcome a Deadlock specifically a Key Lock

Posted: 10 Jul 2013 07:54 AM PDT

Legend:Storefront = the glass & entry door portion of the front of a store like 7-11Bay = the different section of glass that are divided by aluminum verticals that span from the ground to the ceilingHorizontal = A piece of aluminum that spans from the left to right of the inside of a bay.I've got an application that deletes a record from time to time just like what a database does and everything is fine.But I've got a case now where we've added a feature to where 1 - n many of rows could be deleted. What my app is doing is calling a static method for each newly deleted item because that is the way the client is sending the request to my server.It's a loop that does a delete request for each removed / deleted item from the client, and when these request arrive at the server, they arrive one at a time in order, so my static delete method is called for each newly delete request; therefore, it creates a new process (SPID) for each time my stored procedure is called to delete that row/ record, and this leads to a key deadlock.Keep in mind my fellow professionals I'm fairly good at SQL but I'm no guru; however, if someone can point me in the right direction I would be grateful!Let me give you some background on what I'm developing. I working on a CAD program that the CAD UI is written JS, so my brain is already mushy!For this specific situation here is what is happening. I'm allowing the user to add a door to a bay that has horizontals lower than what the door is in height; therefore, the new door covers up the existing horizontals. So, the solution is to remove all horizontals from a bay that are lower to the ground than what a door is in height.[b]Here is a portion of what the CAD UI looks like. I've got the steps in order.[/b]1.) A bay with horizontals that are lower than what the doors height is2.) The door is added to the bay and everything looks as if the horizontals were removed.3.) I removed the door from that bay and the horizontals are still in place, they were never moved because the deadlocks would not allow it.[b]A snap shot reflecting adding a door to the bay with horizontals and then removing the door to see no changes ever took place because of deadlocks[/b][img]http://www.alumcloud.com/h/deadlock-keylock-help.png[/img][b]Diagram of the important portion of this deadlock[/b][img]http://www.alumcloud.com/h/deadlock-keylock-diagram.png[/img][b]A few of the deallock graphs that I was able to capture.[/b][img]http://www.alumcloud.com/h/deadlock-keylock-graph.png[/img][b]The script relevant to this question[/b][url=http://www.alumcloud.com/h/deallock-keylock-script.txt][/url]I've got to get this resolved extremely quickly so any and all suggestions would be great.I'm needing to know how to keep sql from deadlocking when a batch of deletes need to take place on one table.------------------------------------------------------------------------------------------------------Here is the script in text format rather that that link.USE [StorefrontSystem]GO/****** Object: StoredProcedure [Storefront].[proc_DeleteHorizontal] Script Date: 7/10/2013 3:16:10 PM ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE proc [Storefront].[proc_DeleteHorizontal]@HorizontalID INTASSET NOCOUNT ON;BEGIN BEGIN TRAN DeleteHorizontal DECLARE @SizeID INT, @FinishID INT, @SitelineID INT; SELECT @SizeID= h.SizeID, @FinishID = h.FinishID, @SitelineID = h.SitelineID FROM Storefront.Horizontal h with(nolock) WHERE h.ID = @HorizontalID DELETE FROM [Storefront].[Horizontal] WHERE [Storefront].[Horizontal].ID = @HorizontalID; DELETE FROM Storefront.Size WHERE ID= @SizeID; DELETE FROM Storefront.Finish WHERE ID= @FinishID; DELETE FROM Storefront.Siteline WHERE ID= @SitelineID; COMMIT TRAN DeleteHorizontalEND;SET NOCOUNT OFF;GO/****** Object: Table [Storefront].[Finish] Script Date: 7/10/2013 3:16:10 PM ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOSET ANSI_PADDING ONGOCREATE TABLE [Storefront].[Finish]( [ID] [int] IDENTITY(23,1) NOT NULL, [Left] [varchar](30) NULL, [Right] [varchar](30) NULL, [Top] [varchar](30) NULL, [Bottom] [varchar](30) NULL, [Type] [varchar](8) NOT NULL, [Note] [varchar](150) NULL, CONSTRAINT [PK_Finish_ID] PRIMARY KEY CLUSTERED ( [ID] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]GOSET ANSI_PADDING OFFGO/****** Object: Table [Storefront].[Horizontal] Script Date: 7/10/2013 3:16:11 PM ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOSET ANSI_PADDING ONGOCREATE TABLE [Storefront].[Horizontal]( [ID] [int] IDENTITY(11,1) NOT NULL, [Position] [tinyint] NOT NULL, [Name] [varchar](15) NULL, [Floor] [decimal](8, 4) NOT NULL, [SizeID] [int] NOT NULL, [IsFiller] [bit] NOT NULL, [FinishID] [int] NOT NULL, [SitelineID] [int] NOT NULL, [Note] [varchar](150) NULL, CONSTRAINT [PK_Horizontal_ID] PRIMARY KEY CLUSTERED ( [ID] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]GOSET ANSI_PADDING OFFGO/****** Object: Table [Storefront].[Siteline] Script Date: 7/10/2013 3:16:11 PM ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE TABLE [Storefront].[Siteline]( [ID] [int] IDENTITY(1,1) NOT NULL, [LeftCompID] [int] NULL, [RightCompID] [int] NULL, [TopCompID] [int] NULL, [BottomCompID] [int] NULL, [Top] [decimal](6, 4) NULL, [Bottom] [decimal](6, 4) NULL, [Left] [decimal](6, 4) NULL, [Right] [decimal](6, 4) NULL, CONSTRAINT [PK_Siteline_ID] PRIMARY KEY CLUSTERED ( [ID] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]GO/****** Object: Table [Storefront].[Size] Script Date: 7/10/2013 3:16:11 PM ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOSET ANSI_PADDING ONGOCREATE TABLE [Storefront].[Size]( [ID] [int] IDENTITY(231,1) NOT NULL, [HeightFeet] AS ([HeightInches]/(12)) PERSISTED, [HeightInches] [decimal](8, 4) NOT NULL, [HeightPercent] [decimal](7, 4) NOT NULL, [HeightPixels] AS (([HeightInches]/(12))*(25)), [WidthFeet] AS ([WidthInches]/(12)) PERSISTED, [WidthInches] [decimal](8, 4) NOT NULL, [WidthPercent] [decimal](7, 4) NOT NULL, [WidthPixels] AS (([WidthInches]/(12))*(25)), CONSTRAINT [PK_Size_ID] PRIMARY KEY CLUSTERED ( [ID] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]GOSET ANSI_PADDING OFFGOALTER TABLE [Storefront].[Size] SET (LOCK_ESCALATION = DISABLE)GOALTER TABLE [Storefront].[Finish] ADD CONSTRAINT [DF_Finish_Left] DEFAULT (' ') FOR [Left]GOALTER TABLE [Storefront].[Finish] ADD CONSTRAINT [DF_Finish_Right] DEFAULT (' ') FOR [Right]GOALTER TABLE [Storefront].[Finish] ADD CONSTRAINT [DF_Finish_Top] DEFAULT (' ') FOR [Top]GOALTER TABLE [Storefront].[Finish] ADD CONSTRAINT [DF_Finish_Bottom] DEFAULT (' ') FOR [Bottom]GOALTER TABLE [Storefront].[Finish] ADD CONSTRAINT [DF_Finish_Type] DEFAULT ('Anodized') FOR [Type]GOALTER TABLE [Storefront].[Finish] ADD CONSTRAINT [DF_Finish_Note] DEFAULT (' ') FOR [Note]GOALTER TABLE [Storefront].[Horizontal] ADD CONSTRAINT [DF_Horizontal_Position] DEFAULT ((0)) FOR [Position]GOALTER TABLE [Storefront].[Horizontal] ADD CONSTRAINT [DF_Horizontal_Floor] DEFAULT ((0)) FOR [Floor]GOALTER TABLE [Storefront].[Horizontal] ADD CONSTRAINT [DF_Horizontal_IsFiller] DEFAULT ((0)) FOR [IsFiller]GOALTER TABLE [Storefront].[Horizontal] ADD CONSTRAINT [DF_Horizontal_Note] DEFAULT (' ') FOR [Note]GOALTER TABLE [Storefront].[Siteline] ADD CONSTRAINT [DF_Siteline_Left] DEFAULT ((0)) FOR [LeftCompID]GOALTER TABLE [Storefront].[Siteline] ADD CONSTRAINT [DF_Siteline_Right] DEFAULT ((0)) FOR [RightCompID]GOALTER TABLE [Storefront].[Siteline] ADD CONSTRAINT [DF_Siteline_Top] DEFAULT ((0)) FOR [TopCompID]GOALTER TABLE [Storefront].[Siteline] ADD CONSTRAINT [DF_Siteline_Bottom] DEFAULT ((0)) FOR [BottomCompID]GOALTER TABLE [Storefront].[Horizontal] WITH CHECK ADD CONSTRAINT [FK_Horizontal_Finish_FinishID] FOREIGN KEY([FinishID])REFERENCES [Storefront].[Finish] ([ID])GOALTER TABLE [Storefront].[Horizontal] CHECK CONSTRAINT [FK_Horizontal_Finish_FinishID]GOALTER TABLE [Storefront].[Horizontal] WITH CHECK ADD CONSTRAINT [FK_Horizontal_Siteline_SitelineID] FOREIGN KEY([SitelineID])REFERENCES [Storefront].[Siteline] ([ID])GOALTER TABLE [Storefront].[Horizontal] CHECK CONSTRAINT [FK_Horizontal_Siteline_SitelineID]GOALTER TABLE [Storefront].[Horizontal] WITH CHECK ADD CONSTRAINT [FK_Horizontal_Size_SizeID] FOREIGN KEY([SizeID])REFERENCES [Storefront].[Size] ([ID])GOALTER TABLE [Storefront].[Horizontal] CHECK CONSTRAINT [FK_Horizontal_Size_SizeID]GO

management studio

Posted: 10 Jul 2013 06:30 AM PDT

Hi Friends, We installed sql server 2012 on a windows 2012 server last week. We are unable to connect to the 2012 database from SQL 2008/2005 Management studio's. Is there a way to make the 2005/2008 SSMS connect to 2012 db's or is it not forward compatible? Thanks a lot again

[T-SQL] How to add IDENT_CURRENT for foreignkey in procedure?

[T-SQL] How to add IDENT_CURRENT for foreignkey in procedure?


How to add IDENT_CURRENT for foreignkey in procedure?

Posted: 10 Jul 2013 08:22 PM PDT

Hai friends, I ve the table like create table travel_request( request_id int identity primarykey, travel_purpose varchar(10), total_amount varchar(10))and one more table iscreate table onward_journey( onward_journey_id int primarykey, request_id int foreignkey references travel_request(request_id), departuredate datetime, from_place varchar(10), to_place varchar(10))in the table of travel_request insertion is one page of my web appllication,and i wanna catch that request_id pass through onward_joureny table so i made the query like:alter procedure Insert_Journey ( @departuredate datetime, @from_location varchar(50), @to_location varchar(50), @metro nvarchar(50), @trans_all nvarchar(50), @mode_of_travel nvarchar(50), @seat_type nvarchar(50), @no_of_days int, @other_details varchar(50), @status_id int, @request int output ) as BEGIN DECLARE @MaxDate datetime SELECT @MaxDate = MAX(DepartureDate) FROM onward_journey where request_id=@request SELECT @request=IDENT_CURRENT('travel_request ') IF(@MaxDate > @departuredate) begin RAISERROR('Your error message for departuredate should be greater then maxdate',16,1)RETURN END insert into onward_journey(departuredate,from_location,to_location,metro,trans_all,mode_of_travel,seat_type,no_of_days,other_details,status_id) values(@departuredate,@from_location,@to_location,@metro,@trans_all,@mode_of_travel,@seat_type,@no_of_days,@other_details,'2') set @request=IDENT_CURRENT ('travel_request ')return @request endbut its showing null value on my request id......... guide me?

Store Procedure running slow

Posted: 10 Jul 2013 09:43 AM PDT

Hi Experts,I have a Store Procedure which is running slow in Prod but running fine in Stage. I have rebuild the index and updates Statistics but there was no difference in Prod.When I am passing the 'H' Value in Store Procedure its taking 1 Hour and 30 min in Prod and in Stage its taking 11 min I checked the Server configuration Stage is running on 3 Ghz and Prod is 2 Ghz I don't its a Server Problem we moved from a 4.71 environment to a 5.01 environment but nothing was changed in DBs I am attaching the store proc if anyone can help I will appreciate it . Thanks

Check series is valid or not

Posted: 10 Jul 2013 09:12 PM PDT

Hi, I have a scenario in which I have to check that whether I am correct no of series or not...[code="sql"]Create table tbl( ID int identity,number varchar(10),numstatus varchar(10))INSERT INTO tblValues('V001','Active'),('V002','Active'),('V003','Active'),('V004','InActive'),('V005','Active')[/code]I tried in this manner....[code="sql"]Declare @firstno varchar(10) = 'V0001', @scndno varchar(10) = 'V0005'Create table #voucherno( voucherno varchar(10) )INSERT INTO #vouchernoSELECT VoucherNo from tbl WHERE number between @firstno and @scndno SELECT gv.number FROM tbl As gv INNER JOIN #voucherno ro ON ro.VoucherNo = gv.number WHERE gv.numstatus = 'Active'[/code]AS values that i passed in parameters @frstno and @scndno is not in series as v004 is inactive so I should get message invalid series....My query gives me output as V001,v002,V003,v005. I tried with IF EXISTS but didnt get desired output

Help on Date Time Validation

Posted: 10 Jul 2013 06:39 AM PDT

HelloCan someone please share if there are any functions or code to validate the Date in different format settings?Ex:----If I enter the value "9999", the function should validate against the Date Formats ("MM/DD/YYYY", "DD-MMM-YYYY") and return 0, because 9999 is not a valid DateIf I enter the value "01-Jan-9999", the function should validate against the Date Formats ("MM/DD/YYYY", "DD-MMM-YYYY") and return 1.Also is there any common function available to use for similar kind of different requirements?ThanksShuaib

[SQL Server 2008 issues] is there a way to tell when a login was created or revoked?

[SQL Server 2008 issues] is there a way to tell when a login was created or revoked?


is there a way to tell when a login was created or revoked?

Posted: 10 Jul 2013 12:56 PM PDT

Hi sqlcentral colleagues - is there a way to tell when a login was created or revoked? I haven't created any triggers for this purpose. I was wondering if there's default login history info I can pull. Any hope of that? Thanks in advance.

Does anyone have an explanation for this behavior? or another reason to always schema qualify your tables

Posted: 10 Jul 2013 07:29 AM PDT

I was faced this week with a problem. One job was behaving in a odd manner and we could not replicate the issue.In the end the problem was that the job was accessing the wrong table, I just don't know why it was doing that.So here is the scenario:We have a job that runs against a database. That database has a table named DBO.SITE_MASTER and a synonym for the object RPT.SITE_MASTER that points to data on another database.The job in question has a statement like (please note the absence of schema in the table name):SELECT @ID=SITEID from SITE_MASTER where SITE_NAME=@SITE_NAMEAfter trying everything I could think of I noticed that whenever I executed that statement (with a sysadmin like account) I would access the DBO table. Whenever the SQL Agent job (running as "sa") executed that statement, it would access the synonym and return different results.The fix was easy, and should be in place form the start (just fully qualify the table with the schema), but does anyone know WHY this is happening? I thought that SQL would check for the schema with the same user name, and if that was not available would always default to DBO.Why is SQL in this case defaulting to a non-default schema, and only for the SQL Agent user?Thanks in advance

Extract String between Special characters

Posted: 10 Jul 2013 09:23 AM PDT

Hi All, I have a string like this Building Management - Ex. Existing Facility\Keys & locks\Project Co to ensure that 400 complete sets of keys are available at all times.now my requirement is to extract string before first \ ,second \ and third \ . So my results would be like this Building Management - Ex. Existing FacilityKeys & locksProject Co to ensure that 400 complete sets of keys are available at all times.what is best way of achieving this in sql server 2008.

Schema Diagram

Posted: 09 Jul 2013 11:53 PM PDT

Hi Has anyone ever had to reverse engineer a schema diagram from a database before? If so, what tool did you use? I have Toad for SQL Server which I'm currently trying to figure out if it will do as I want.Thanks.

Insert bulk failed due to a schema change of the target table.

Posted: 10 Jul 2013 07:21 AM PDT

Hello Expert.First time I used sqlbulkcopy its performance is impressive, however my application threw a SQL exception after processed about 500,000 records. The error stated "Insert bulk failed due to a schema change of the target table." which I don't understand why, data being inserted into the same table, and why it processed 500,000 records with out issue, but not the rest which I cant understand.Here is the chunk of VB.Net code that does the bulk copy. Notice that MyDestTable has a couple more fields that I didn't want them to be mapped. all fields in the MySourceDataTable table are specified in the mapping.Dim sqlBulk As New SqlBulkCopy(_connectionString) sqlBulk.DestinationTableName = MyDestTable sqlBulk.ColumnMappings.Add("DataOwnerID", "DataOwnerID") sqlBulk.ColumnMappings.Add("ObjectID", "ObjectID") sqlBulk.ColumnMappings.Add("ObjectTypeID", "ObjectTypeID") sqlBulk.ColumnMappings.Add("PropertyName", "PropertyName") sqlBulk.ColumnMappings.Add("Pvalue", "Pvalue") sqlBulk.ColumnMappings.Add("UpdateIDRefreshed", "UpdateIDRefreshed") sqlBulk.ColumnMappings.Add("UpdateIDModified", "UpdateIDModified") sqlBulk.ColumnMappings.Add("Attribute", "Attribute") sqlBulk.ColumnMappings.Add("POrder", "POrder") sqlBulk.WriteToServer(MySourceDataTable) sqlBulk.Close()Anyone run into this type of error while using SQLBulk copy? I did lot of googling but didn't find anything points to the right direction.Thanks in advanced.

Data center migration

Posted: 10 Jul 2013 07:35 AM PDT

I hope this forum is "general" enough for this question. I figure most people here have experienced this issue in one way or another.We are migrating our data center and we are concerned about our SQL servers with relative data.Our goal is to move the server as smooth as possible to the new location, which is only about 200 yards around the corner, but there are bumps, door entries, rough sidewalks, etc.Does anybody on here have some best practices regarding server transportation he or she would be willing to share?Thanks in advance.

how to modify sql job to remove extra information coming in text file

Posted: 10 Jul 2013 07:26 AM PDT

I am exporting the sql query result set to a text file and its writing without the issue, i want to eliminate lot of extra information it is writing For example Job 'myNIC_PROD_ActiveUsers_In_Last5Minutes' : Step 1, 'Active_Users' : Began Executing 2013-07-04 18:25:47 [b]NumberRows Time_stamp ----------- ------------------------------------------------------ 39 2013-07-04 18:25:47.630[/b] (1 rows(s) affected) So i only need to see Bold text in this post

linked server issue

Posted: 10 Jul 2013 01:04 AM PDT

HiCan anybody advise on the following error :[quote]OLE DB provider "SQLNCLI10" for linked server "server1" returned message "The partner transaction manager has disabled its support for remote/network transactions.".Msg 7391, Level 16, State 2, Line 2The operation could not be performed because OLE DB provider "SQLNCLI10" for linked server "server1" was unable to begin a distributed transaction.[/quote]Any pointers would be great. Thanks

Importing Text file madness

Posted: 10 Jul 2013 06:09 AM PDT

OK. This one has driven me mad for the past couple of hours. I am working on a new & improved web site for this State Agency and converting some old Informix text-file based databases to SQL Sever and .NET.The task is simple. Import a text file into a SQL Server 2008 Table.I am trying to import this file into a SQL Server 2008 Table:http://www.mvdb.virginia.gov/Downloads.txtAnd I am getting these errors:* Error 0xc02020a1: Data Flow Task 1: Data conversion failed. The data conversion for column "Description" returned status value 4 and status text "Text was truncated or one or more characters had no match in the target code page.". (SQL Server Import and Export Wizard) * Error 0xc020902a: Data Flow Task 1: The "Source - Downloads_txt.Outputs[Flat File Source Output].Columns[Description]" failed because truncation occurred, and the truncation row disposition on "Source - Downloads_txt.Outputs[Flat File Source Output].Columns[Description]" specifies failure on truncation. A truncation error occurred on the specified object of the specified component.(SQL Server Import and Export Wizard) * Error 0xc0202092: Data Flow Task 1: An error occurred while processing file "C:\.....\Downloads.txt" on data row 2. (SQL Server Import and Export Wizard) * Error 0xc0047038: Data Flow Task 1: SSIS Error Code DTS_E_PRIMEOUTPUTFAILED. The PrimeOutput method on Source - Downloads_txt returned error code 0xC0202092. The component returned a failure code when the pipeline engine called PrimeOutput(). The meaning of the failure code is defined by the component, but the error is fatal and the pipeline stopped executing. There may be error messages posted before this with more information about the failure. (SQL Server Import and Export Wizard)From what I can gather, my "Desciption" field is being truncated. Here's the weird part. The txt file comes another SQL Server (test machine) 2008 table. Description is defined as being varchar(200). So it the table/field I'm trying to import INTO. In fact, I doubled it to 400 just to see what it would happen. No luck. Same errors.Any ideas? Going nuts here.

find session

Posted: 10 Jul 2013 01:22 AM PDT

Hi friends, Our database server(windows 2008R2 4GB 64-bit) goes up to 98% physical memory and about 3.5G from sqlservr.exe. Max server memory is set to 2GB for sql server. Users are facing performance issues.. Is there a way to find out which process is using up most memory from sql server? Also, are there any options to resolve this other than increasing RAM?Thanks a lot

Total Beginner Question

Posted: 10 Jul 2013 06:33 AM PDT

Believe me when I say that I have googled this and searched this forum up and down and either don't understand or can't find the answer I am looking for. I have a simple SQL 2008 database that receives names, companies and the date when the company representatives visit request expires. I am trying to write a query that will return rows of reps whose visit request expires in 30 days. What I have written is SELECT vrExpdate - 30 DAYSFROM mydatabaseIt returns an error stating Operand type clash: date is incompatible with int. The data type for vrExpdate is "Date". I understand that an integer isn't compatible with a date but what I don't understand is how to write this query. I have tried unsuccessfully using every "DATE" function I can find...from DATEADD to DATEDIFF and everything in between.Any help will be greatly appreciated.

Raid 1 or raid 10

Posted: 10 Jul 2013 03:12 AM PDT

Hello.What is the best, Tempdb and Ldf's users databases in a Raid 10 with two volumes or one Raid 1 for each?Thanks.

Red lines under third occurance of a table name

Posted: 10 Jul 2013 02:38 AM PDT

Hello. I have an annoying problem and I can't find anything about it.In scripts I have, that are templates created by my co-workers, the first occurance of a table name, ex: dbo.Exception_Ibank, is fine.The third occurance has a red squiggly line under it as do all following occurances. If I move my mouse over the table name, it says that it can't find it. The script runs properly, though. Also, all of the field names of the columns in that table have red lines under them, too.I've tried to clear the cache, which didn't do anything.This isn't a performance issue. It's just annoying.Any help would be greatly appreciated.Bert

Updating SQL table using SSRS

Posted: 10 Jul 2013 01:00 AM PDT

Hi everyoneI have the following table in sql server:CREATE TABLE [DBO].[SHIFTS]( [WEEK_ENDING] DATETIME NULL,[FORENAME] VARCHAR(50) NOT NULL ,[SURNAME] VARCHAR(50) NOT NULL,[EMP_ID] VARCHAR(10) NOT NULL ,[DEPARTMENT] VARCHAR(50) NOT NULL,[SHIFT] VARCHAR(20) NOT NULL,[HOURS] INT NULL)I was wondering whether it was possible to create a front end utility in SSRS that could alter the [DEPARTMENT] ,[SHIFT] and [HOURS] fields back in the base sql table. Ideally I'd like the ability for the user to type in the requisite changes which would then update the table. The report will be viewed by Managers and the purpose of this utility will be for them to check, alter and approve the hours worked by their staff. I know its possible to update tables using SSRS but not sure whether it can be done by direct entry via SSRS. Thanks in advance,BO

Import data from multiple Excel sheets to multiple Tables using SSIS

Posted: 09 Jul 2013 08:33 PM PDT

Hi,I have a excel file that has multiple sheets and I need to import data from each seperate sheet to a seperate table using SSIS. E.g. Sheet A data should go to Table A and Sheet B data should go to Table B. We are doing some data unpivoting also before sending it to table.Can somebody help me to achieve this?

Sql server Mirroring without witness Server

Posted: 10 Jul 2013 02:20 AM PDT

HI,I need to start mirroring the databases without witness server,Can i please have instructions from scratch to end kind of step by step.Regards

Replication DB - Dead lock issue

Posted: 29 Jun 2013 03:32 PM PDT

Hi,We have One Database which is a Replication Db, sometimes during beginning of the month, lot of user activities going and we having Dead lock issue.Any one has idea how to prevent the dead lock in Replication DB?We have to manually kill the user session one by one but if someone having same kind of issue and have any idea?Thanks,

How to update Flag for maximum amount in a a group

Posted: 10 Jul 2013 12:27 AM PDT

Create Table #Temp(Pk_Id Int Identity(1,1),Lnno Int,Amount Int,Flag Char(1))Insert Into #Temp(Lnno,Amount)Values (1,5),(1,10),(2,20),(2,25)Select * from #TempHi, My requirement is,I want to update Flag as 'Y' for the Lnno which has maximum amount. Please help this is urgent to me. Thanks in Advance!

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

Posted: 15 Nov 2012 05:53 PM PST

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()

script

Posted: 09 Jul 2013 11:49 PM PDT

i would like to find the above details DB names, last backup finished date , backup size of all the databases , free space in data files in all the databases, is any script to achieve this . .

Rounding issue

Posted: 30 May 2013 01:21 PM PDT

Hi everyone,I have problem with rounding. There is a table[code="plain"]CREATE TABLE [dbo].[Fin3PaymentDisb]( [PaymentID] [bigint] NOT NULL, [Currency] [char](3) NOT NULL, [Amount] [money] NOT NULL, [Rate] [float] NOT NULL, [CurrencyPay] [char](3) NULL, [RatePay] [float] NOT NULL, [AmountPay] AS ([Amount]*[Rate]), CONSTRAINT [PK_Fin3PaymentDisb] PRIMARY KEY CLUSTERED [/code]with valuesAMOUNT = 3875.0000RATE = 0.17836AMOUNTPAY = 691.145 And this query returns record[code="plain"]SELECT P.*FROM Fin3Payment P INNER JOIN ( SELECT PaymentID, SUM(AmountPay) AS Amount FROM Fin3PaymentDisb GROUP BY PaymentID ) AS L ON L.PaymentID = P.PaymentID AND ROUND(Round(L.Amount, 2) - ROUND(P.Amount - P.Offset - P.SetDisc, 2), 2) <> 0[/code]where PaymentAmount = 691, Offset = -0.15 and SetDisc = 0, i.e. 691.145 is rounded to 691.14. But in the query[code="plain"]SELECT ROUND(691.145, 2)[/code]result is 691.15.What could be the problem here? It runs on MS SQL 2005 Express SP2.Thanks.

Wednesday, July 10, 2013

[SQL Server] Count value once in 30 days

[SQL Server] Count value once in 30 days


Count value once in 30 days

Posted: 10 Jul 2013 06:05 AM PDT

Hello,If I have a customer respond to the same survey in 30 days more than once, I only want to count it once. Can someone show me code to do that please?[code="sql"]CustomerID SurveyId ResponseDatecust1 100 5/6/13Cust1 100 5/13/13Cust2 100 4/20/13Cust2 100 5/22/13[/code]Then output should be like this:[code="sql"]CustomerID SurveyId CountSurveyCust1 100 1Cust2 100 2[/code]

Dynamic WHERE statement if stored procedure parameter is null

Posted: 09 Jul 2013 11:05 PM PDT

I have the stored procedure with @StartDate and @EndDate parametersmy WHERE statement is using those parameters to filter out dataWHERE condition1 and SomeDate >= @StartDate and SomeDate <= @EndDate and condition2However when @StartDate or @EndDate is null or empty string then WHERE statement should look like belowWHERE condition 1 and condition2I was trying already to do it with CASE of IF statement but without success so far.

non identity auto increment field

Posted: 10 Jul 2013 02:19 AM PDT

Hi all, I"m very new to SQL and have been searching the forums but haven't found what I'm looking for. I need to create 2 additional auto increment fields in a table. We are using SQL 2008 R2. I think I need to use a trigger to do this, but I'm not sure exactly the best way to do this. Here is my table structure.Employee_Number is IDENTITY fieldFirst_NameLast_NameLibrary_Barcode - needs to be auto incrementFood_Barcode - - needs to be auto incrementThe 2 barcode fields need to be auto increment fields when a new record is added. I was thinking of having another table that would contain the last value used for these 2 fields and then create a tirgger when a new record was added that would read the values and add 1 and insert the new value into their respective barcode fields above and then update the table containing the last number used. I wasn't sure if this was the best method to perform what I'm looking for. The numbers for these fields are only added when a new record is created, they will never change.Any help would be appreciated.Kevin

Change row values to columns

Posted: 10 Jul 2013 05:24 AM PDT

Hello,I'm looking for some help with SQL code.I have a SQL query with many JOINS which returns three or more AccountIDs for a customer, so right now it's like this:[code="sql"]CustomerId CustomerName AcctId ManyOtherColumnsForCustomerCust1 Peter 123Cust1 Peter 345Cust1 Peter 567[/code]I want to change it to look like this:[code="sql"]CustomerId CustomerName AcctId1 AcctId2 AcctId3Cust1 Peter 123 345 567[/code]Can someone pelase help me with code to get data as in the 2nd output? Thanks

Distinct Keyword

Posted: 09 Jul 2013 11:40 PM PDT

I am wanting to add a distinct keyword to this statement and I am not sure how or where exactly to add it.[code="vb"] SELECT Location.[Stack ID], Location.Location, Location.[Move Date], Location.[Move Time]FROM LocationWHERE (((Location.[Move Date])=[Please enter the date])); [/code] I am needing to eliminate duplicates in the [Stack ID] fields within the Location table.

Search This Blog