Thursday, April 18, 2013

[Articles] Asking for Interview Questions

[Articles] Asking for Interview Questions


Asking for Interview Questions

Posted: 17 Apr 2013 11:00 PM PDT

When someone asks for interview questions on the web, it seems many people are upset. But should they be? Steve Jones points out there are different sides to this.

[MS SQL Server] Issue with Linking Servers

[MS SQL Server] Issue with Linking Servers


Issue with Linking Servers

Posted: 17 Apr 2013 08:49 AM PDT

This is my current situation. I have job scheduled to run every morning that collects data from various servers to a local database on Server A and then we will use that data for reports, etc. The owner of the job is the same user as the SQL service service account and this account has access to all our sql servers and runs other jobs without any issues. When the job is ran I receive this error in the history log: Executed as user: domain\sqluser. Login failed for user 'sa_Link'. The user is not associated with a trusted SQL Server connection. [SQLSTATE 28000] (Error 18452). The step failed.I have created links to each of the server's I am connecting to. I have used the following to create the links between the servers: EXEC sp_addlinkedserver @server=N'ServerB', -- Remote Computer Name @srvproduct=N'', -- Not Needed @provider=N'SQLNCLI', -- SQL Server Driver @datasrc=N'ServerB'; -- Server Name And InstanceThen under server objects-Linked Servers I see the linked server. For the Security tab I don't have any users in the local login. The only change here I have done is select the "Be made using this security context" with the sa_link user account and password. This is a local SQL user and is both on server A and server B with the same password. Under server options I have also enabled RPC and RPC OutNow I have setup the sql domain service account setup to delegate via kerberos due to a need the occurred between to other server's and a programmers PC (2nd hop not liking NTLM, etc). But since this is only one hop NTLM or Kerberos will work just fine. I've been trying to figure out what I am missing or did incorrectly that isn't allowing the SP's in the job to run.

service pack

Posted: 17 Apr 2013 11:03 AM PDT

I am using SQL server installation to repair an exiting crashed SQL server 2008 Sp3My question is after I do the repair which is from installation media , do I still need to apply service pack 3?Thanks,

DBcreator

Posted: 18 Apr 2013 02:32 AM PDT

We have a build process , the build account is a dbcreator, after it create the database, it cannot access the objects in it, why is that?Thanks

Have upgraded from 2005 to 2008R2 but still getting security updates for 2005

Posted: 10 Apr 2013 12:06 AM PDT

Hi there,We've recently upgraded a 2005 SQL cluster (active / active) to 2008 R2. There still seems to be SQL 2005 client tools including SSMS but the version in the registry setting and on the SQL instances is 10.50.4000. I just recently checked for security updates for the server and I was troubled to see that one of them coming up is "Security Update for SQL Server 2005 Service Pack 4 Failover Clustering".Has anyone else experienced this or why this is happening and how to resolve this?Thanks,Mike

Reindex task taking for ever

Posted: 09 Apr 2013 06:11 PM PDT

SQL Server 2008 R2 - 10.50.2500. We have a Database, about 35 GB in size, which has got several tables and indexes. I ran a report 'Index Physical Statistics' and it came up with recommendation for rebuild couple of indexes. I tried to rebuild these indexes, all but few wouldn't. The reindex on these few indexes seems to be taking for ever and i had to cancel the reindex task. Below is the detail of the index on which reindex task was taking for ever:IndexName Index Type Partitions Depth Operation RecommendedXXXXXX , Nonclustered, 1, 2, Rebuild Partition Type, Avg Frag%, #Fragments, Avg Pages per Frag, # Pages 1, 50, 2, 1, 2Any ideas? Thanks,Ravi

Min and Max server memory

Posted: 17 Apr 2013 07:04 AM PDT

Am a junior DBA and We have an issue from last couple of days. We have a server of Windows 2003 Standard Edtion of x64 bit with SP2. SQL Server is of 32bit running. Physical Memory on the server is 0f 4GB and SQL now running out of memory. Can we enable the AWE on a 64 bit OS machine where SQL is of 32 bitPlease suggest me

Collation check

Posted: 17 Apr 2013 09:42 AM PDT

How do I amend this to only show me tables, select DISTINCT TABLE_NAME from INFORMATION_SCHEMA.COLUMNSWHERE COLLATION_NAME <> 'SQL_Latin1_General_CP850_BIN'AND TABLE_NAME <> 'syn%' order by TABLE_NAME ASC

[SQL 2012] Sql 2010 AlwaysOn Availability Group

[SQL 2012] Sql 2010 AlwaysOn Availability Group


Sql 2010 AlwaysOn Availability Group

Posted: 17 Apr 2013 05:48 PM PDT

Hello Guys,I am about to implement sql server 2012 AwalysOn Availability group and my question is around storage. Does AlwaysOn availability group work with Shareddisk or only disk that are local to the computer(node)?Thank you

EXTERNAL REFERENCE OF EXECUTE PACKAGE TASK OF 2012 ISSUE

Posted: 17 Apr 2013 05:30 PM PDT

while using execte pakage task in 2012 i face a problem. The project reference in this task works fine but external reference is showing error and i have to use this external reference if i try to call a child pkg from parent pkg when both the pkg are in different project solutions. pls give me solution of above issue.....

AlwaysOn: automatically add new databases to SQL 2012 AlwaysOn by script/T-SQL or PowerShell

Posted: 17 Apr 2013 06:34 AM PDT

Greetings! I've installed and successfully configured our SQL 2012 AlwaysOn 2-node servers for our new "Intranet" that is coming out. I've gotten AlwaysOn working great, and our Front End servers for the Intranet will be using SharePoint 2013. The glitch is that SharePoint 2013 is configured to add databases automatically to our SQL Server 2012 back end, but NOT to AlwaysOn. In reading about this and in contacting Microsoft MSDN support, the default answer is "you must manually find, select, back-up and then add those new databases individually to get them into AlwaysOn." But wait; that can be quite a task, constantly checking the SQL Back-end servers to see what databases were created, then having to add them into AlwaysOn, 7/24! I'm looking for a script or process that will check for new databases, back those new databases up in FULL mode, (for being added to AlwaysOn, of course) then add those databases to AlwaysOn, all automatically. Or have this run every...1-2 hours? (without user intervention)What I've come up with so far is this script that actually identifies the newly-added databases, (not yet in AlwaysOn), and then backs them up to a shared location. My next task is to find those newly-added databases and through the various processes needed, get them added to AlwaysOn. This will involve some sort of looping action, I imagine. I'm not a T-SQL/scripting guru; is there any solution or script that I might access that would do this? (add databases to AlwaysOn automatically)? Please advise, I'm sure I'm not the first person to have this issue. I have seen previous posts on various Internet Sites, and the solution is "sure, go ahead and just script that!". Thanks, but I need just a little more detail there.Thanks again, -AllenDECLARE @name VARCHAR(50) -- database name DECLARE @path VARCHAR(256) -- path for backup files DECLARE @fileName VARCHAR(256) -- filename for backup -- specify database backup directorySET @path = '\\atel-web-be2\backups\' DECLARE db_cursor CURSOR FOR select name from sys.databaseswhere group_database_id is null and replica_id is null and name not in('master','model','msdb','tempdb') OPEN db_cursor FETCH NEXT FROM db_cursor INTO @name WHILE @@FETCH_STATUS = 0 BEGIN SET @fileName = @path + @name + '.BAK' BACKUP DATABASE @name TO DISK = @fileName FETCH NEXT FROM db_cursor INTO @name END CLOSE db_cursor DEALLOCATE db_cursor

[T-SQL] avoiding duplicates in comma separated values column

[T-SQL] avoiding duplicates in comma separated values column


avoiding duplicates in comma separated values column

Posted: 18 Apr 2013 12:36 AM PDT

Hi Guys,I am working on stored proc to update master table from temp table and getting following issue. [b]temp_table[/b]sa, Logger, Reader[b]master_table[/b]sa, Reader[b]Reqired_Output_On_master_table [/b]sa, Reader, LoggerSo i only want to add comma seperated value when it is not already present in master table. (to avoid duplicate entry). i think i have to use CHARINDEX but don't know exact implementation. Any help from you guys will be gr8...Thanks,

Is there a TVP equivalent to an optional parameter?

Posted: 18 Apr 2013 01:15 AM PDT

I'm trying to help my client solve an issue with frequent "breaking changes" to procedures that use table-valued-parameters. The calling code is in a highly branched environment, but due to resource constraints, there is only one SQL Server database environment for all the development branches and the production-equivalent testing environment.The resulting issues have been dealt with largely through the use of optional parameters. The calling code doesn't need to know about optional parameters that it doesn't use.Recently, one of the business lines implemented a number of procedures using TVPs. This particular product is unique in the business for processing large batches, and it saw significant performance gains from the TVPs. Usage of TVPs is new for this client.But now we are dealing with the problem of needing "optional" columns on the table definition. Different development branches need different optional columns, and they are headed out to production at different times. But there's no such thing as an optional column defintion. The calling code (C#) has to know about the new column, even if it's nullable. Is there a technical solution to this problem? Anything that I'm missing?

TOP 25% rows by Weightage

Posted: 17 Apr 2013 02:10 AM PDT

I have a table as below. I need to find the members which are in the bottom quartile (25%) of the weights in each class[code="other"]ClassID MemberID Weight A 1 10A 2 20A 3 40A 5 25A 6 15A 8 10B 1 50B 2 10B 3 60B 6 400[/code]For above example, total weight of class A is 120. If I order by weight and pick the top ones such that their summed weight comprise less than or equal to 25% of total weight (25% of 120 = 30 for class A)I would pick Members 1 and 8. If I include member 6, it would exceed 25% (30)The output I need is[code="other"]ClassID MemberID Weight A 1 10A 8 10B 1 50B 2 10B 3 60[/code]What would be the best way of achieving this in TSQL (Sql server 2008)?Hope the question is clear

Trigger that collects data from two tables

Posted: 12 Apr 2013 08:35 AM PDT

Hi,Is it possible to create an After Update trigger on table A that can gather both the delete and insert data for the After Update from columns A.1, A.2, A.3 when A.3 is updated to NULL? I need that plus the delete and insert data from columns B.1 and B.2 from table B as well when column A.3 is updated and set to NULL? I have the trigger below that will get me what I need from table A but is it possible to also get the data from table B from this trigger? In other words, I'm trying to figure out how to populate the Table B OldWorkFlowStepId and NewWorkFlowStepid columns that are created in the CONTAINER_DEBUG table and declared as variables. The OldWorkFlowStepId value needs to be taken when the delete.CurrentStatusId is taken from the first table and the NewWorkflowStepId value needs to be taken when the insert.CurrentStatusId is taken from the first table. How would I go about that? I am trying to troubleshoot a column that is getting set to NULL when it shouldn't and I'm trying to trap exactly where in the workflow this is happening.[code="sql"]DROP TABLE CONTAINER_DEBUGGOCREATE TABLE CONTAINER_DEBUG( ContainerId CHAR(16) ,ContainerName VARCHAR(256) ,OldCurrentStatusId CHAR(16) ,NewCurrentStatusId CHAR(16) ,OldLastCompletedTaskId CHAR(16) ,NewLastCompletedTaskId CHAR(16) ,OldWorkflowStepId CHAR(16) ,NewWorkflowStepId CHAR(16) ,LastActivityDate DATETIME )GODROP TRIGGER CONTAINER_TRG_BUGOCREATE TRIGGER CONTAINER_TRG_BUON CONTAINERAFTER UPDATE AS IF ( UPDATE (CurrentStatusId) )BEGIN -- DECLARE @OldCurrentStatusId CHAR(16); DECLARE @NewCurrentStatusId CHAR(16); DECLARE @OldLastCompletedTaskId CHAR(16); DECLARE @NewLastCompletedTaskId CHAR(16); DECLARE @OldWorkflowStepId CHAR(16); DECLARE @NewWorkflowStepId CHAR(16); -- SELECT @OldCurrentStatusId FROM deleted; -- SELECT @NewCurrentStatusId FROM inserted; -- IF ( ISNULL(@OldCurrentStatusId,'XXX') <> 'XXX' AND ISNULL(@NewCurrentStatusId,'XXX') = 'XXX' ) -- BEGIN -- INSERT INTO CONTAINER_DEBUG ( ContainerId ,ContainerName ,OldCurrentStatusId ,NewCurrentStatusId ,LastActivityDate ) SELECT i.ContainerId ,i.ContainerName ,d.CurrentStatusId ,i.CurrentStatusId ,i.LastActivityDate FROM Inserted i INNER JOIN Deleted d ON i.ContainerId = d.ContainerId -- RAISERROR ('CurrentStatusId is set to NULL - Aborting...', 16, 10); -- END; --END;GO[/code]

query Suggestion please

Posted: 17 Apr 2013 05:40 AM PDT

My requirement is to update the ApplicationID column if Server matches and Insert the server name and ApplicationID data if server has more than one applicationID.Here is the case:Server can have multiple App ID'swe need to check as follws.1. Check the server name matches or not. 2. If server matches check the corresponding App ID. If app ID is null then update3. If server matches and has multiple APPID's insert servername and AppIDex:ApServer-----------Server|||||AppIDAAABBB|||||1000AAABBB|||||1005ASFQRE|||||1001AGSFSD|||||1002CCCDDD|||||1003CCCDDD|||||1009LUT2013------------Server|||||AppIDAAABBB|||||NULLASFQRE|||||NULLAGSFSD|||||1002CCCDDD|||||NULLOUTPUT TABLE LUT2013 SHOULD LOOKE LIKE BELOW.Server|||||AppIDAAABBB|||||1000AAABBB|||||1005AGSFSD|||||1002CCCDDD|||||1003CCCDDD|||||1009Please give me idea to start working on this requirement.thanksAswin

Unexpected results in Full Text Search in SQL Server 2008R2

Posted: 17 Apr 2013 04:33 AM PDT

Hi All,I have a full text search SP to search a field that contains English&French. But the result of the search was not expected. Is it because that contains multi languages. The catalog I defined in Language for Word Breaker was "Neutral". Here is my Full text search query below (SQL Server 2008 R2 -64bits)Declare @sSearchString nvarchar(1000), @sLanguage varchar(30), @iRank intset @sLanguage = 'Neutral'set @iRank = 100set @sSearchString = N'"Code de procédure civile"'SELECT t1.test_id, t1.Rtn1, t1.Rtn2, t2.s_Name, t2.s_Address, t_Master.rank as RankingFROM test1_Master t1 Inner JOIN test2_Client t2ON t1.test_id = t2.test_id Inner JOIN test_Table3 t3ON t2.legis_id = t3.legis_idinner join FREETEXTTABLE (test1_Master, (Rtn1,Rtn2),@sSearchString, Language @sLanguage, @iRank) as t_Masteron t1.test_id = t_Master.[key]where t1.Rtn1 is not NULL and t1.Rtn2 is not NULLunion allSELECT t1.test_id, t1.Rtn1, t1.Rtn2, t2.s_Name, t2.s_Address, test_Address.rank as RankingFROM test1_Master t1 Inner JOIN test2_Client t2ON t1.test_id = t2.test_id Inner JOIN test_Table3 t3ON t2.legis_id = t3.legis_idinner join FREETEXTTABLE (test2_Client, (s_Name,s_Address),@sSearchString, Language @sLanguage, @iRank) as test_Addresson t1.test_id = test_Address.[key]where t2.s_Name is not NULL and t2.s_Address is not NULLif I changed the Language to English or French, the number of rows returned were different but was not able to predict what the returned results.btw, I am new to Fulltext search programming. Hope the expert can give me some suggestion. Also I would like to have google search type of results. Can someone point out my error and would be great if you have some sample scripts. Thanks in Advance!Jim

can we compare time AM/PM time format?

Posted: 17 Apr 2013 01:34 AM PDT

Hi,Can we compare AM PM date format?Example datecolumn > 12:00PM and datecolumn < 1:00PM.Here datecolumn is varchar. Pleae suggest any idea?ThanksAbhas.

[SQL Server Data Warehousing] T-SQL SCD2


Here is the query i am using in case if it helps.


To give you little more scenario  on my request  : Our Data warehouse is very traditional approach of ETL , We have update statments that does lookup and update the Foriegn keys.


My first update statments goes and finds an employee based on a logic of Data Entry



Update dbo.SFWP
Set EmployeeID = we2.EmployeeSK
from dbo.SFWP a
Inner Join WMDM.dbo.WMDM AT
on a.AssignedTaskID = AT.AssignedTaskID
Inner join WMDM.dbo.Employee we1
on AT.EmployeeID = we1.SK
Inner Join WMDM.dbo.Employee we2
on we1.NK = we2.NK
and Src_EntryDate >= we2.EffectiveBeginDTM and
Src_EntryDate <= we2.EffectiveEndDTM

Apparently for some reason some employees cannot be matched because  our employee table has this condition not met because of missing records


and  Src_EntryDate >= we2.EffectiveBeginDTM and
Src_EntryDate <= we2.EffectiveEndDTM


So, my new query i am trying to take a previous or Next record and find employee ID and update it.



wITH CustCTE as
(
select
We2.SK,
We2.NK,
We2.EffectiveBeginDTM,
We2.EffectiveEndDTM,
ROW_NUMBER() OVER (PARTITION BY We2.NK ORDER BY We2.EffectiveBeginDTM) RowNum
from dbo.SFWP a
Inner Join WMDM.dbo.WMDM AT
on a.AssignedTaskID = AT.AssignedTaskID
Inner join WMDM.dbo.Employee we1
on AT.EmployeeID = we1.SK
Inner Join WMDM.dbo.Employee we2
on we1.NK = we2.NK
Where
Src_EntryDate < we2.EffectiveBeginDTM or
Src_EntryDate > we2.EffectiveEndDTM
and a.EmployeeID is NULL
)
,
CustCTE1 as (
Select
a.SK
,a.NK
,a.EffectiveBeginDTM
,a.EffectiveEndDTM
,a.RowNum

From CustCTE a
Union All
Select
Curr.SK
,Curr.NK
,Curr.EffectiveBeginDTM
,Curr.EffectiveEndDTM
,Curr.RowNum

From CustCTE Curr
Inner Join CustCTE1 Prev
on Curr.NK = Prev.NK
and Curr.RowNum = Prev.RowNum-1
)
select * From CustCTE1

But i am not getting the same thing as i expect..


Any help in this matter will be highly appreciated.


thank you in advance



.

social.technet.microsoft.com/Forums

[SQL Server] Using Dynamic SQL in Stored Procedures



Weekly SQL Server newsletter with articles, forum posts, and blog posts via email. Subscribers receive our white paper with performance tips for developers.



SQLTeam.com Articles via RSS


SQLTeam.com Weblog via RSS



.

sqlteam.com

[SQL Server 2008 issues] job fails with linked server

[SQL Server 2008 issues] job fails with linked server


job fails with linked server

Posted: 17 Apr 2013 07:22 PM PDT

Hello everybody.I'm getting an error in a job that I can't explain myself.I have two servers: ERPSERVER and STAGINGSERVERon STAGINGSERVER I run scheduled jobs that get data from ERPSERVER so to elaborate and provide them to other databases.on ERPSERVER I have defined a view that prepares the data to be provided to STAGINGSERVERNow, on STAGINGSERVER I have a scheduled job that queries ERPSERVER and use those data to feed my ETL. ERPSERVER is defined as linked server on STAGINGSERVER.What happens is that somewhen I got errors on the job.This is part of the View's Code:[code="plain"]SELECT Partite.CreditNote,[b] 1 AS exchangerate,[/b] CONVERT(NVARCHAR(100), Partite.Salesperson) AS owneridExt,......FROM dbo.MA_PyblsRcvbls AS Partite INNER JOIN dbo.MA_PyblsRcvblsDetails AS PartiteRighe......[/code]the code inside my job is the following[code="plain"]SELECT [CreditNote] ,[exchangerate] ,[owneridExt].........INTO #_OPENITEMSFROM [ERPSERVER].DBNAME.dbo.VW_CRM_OpenItem[/code]this is the error I get:[code="plain"]Step ID 1Server STAGINGSERVERJob Name Import_1D_19Step Name ETL OpenItem Duration 00:00:10Sql Severity 16Sql Message ID 3621Operator Emailed Operator Net sent Operator Paged Retries Attempted 0MessageExecuted as user: domain\crmsqlserver. [b]Cannot insert the value NULL into column 'exchangerate',[/b] table 'tempdb.dbo.#_OPENITEMS_______________________________________________________________________________________________0000000045DB'; column does not allow nulls. UPDATE fails. [SQLSTATE 23000] (Error 515) The statement has been terminated. [SQLSTATE 01000] (Error 3621). The step failed.[/code]I'm out of resources, because I can't understand how it can the column 'exchangerate' be NULL.If I execute the ETL Query from SSMS, all runs without any problem. If I run the query then I run the job it runs without problemsMay it be a network/authentication problem?Thank you in advance.

Update statement really slow but only on the first execution

Posted: 17 Apr 2013 12:32 AM PDT

Hi,I have a standard update statement that updates one row at a time. The table size is 340,000 rows, so it's large but it's not huge.The first time I run the query it takes a very long time considering its a simple update, around 40 seconds. However the second time I run the same update statement it takes less than a second.I just wondered if anyone might be able to assist in letting me know where I might be able to start looking to find out why the update statement is so slow?Any help would be appreciated.Thanks,Lewis

Weekly report through whole year

Posted: 10 Apr 2013 10:51 PM PDT

Hi thereI have 2 tables and sample data:--------------------------------------------------------------------------------------------------------------------------------------------------------CREATE TABLE [dbo].[tblProduct]( [ProductID] [int] IDENTITY(1,1) NOT NULL, [Name] [varchar](50) NOT NULL, CONSTRAINT [PK_tblProduct] PRIMARY KEY CLUSTERED ( [ProductID] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]--------------------------------------------------------------------------------------------------------------------------------------------------------CREATE TABLE [dbo].[tblOrder]( [OrderID] [int] IDENTITY(1,1) NOT NULL, [ProductID] [int] NOT NULL, [OrderDate] [datetime] NOT NULL, CONSTRAINT [PK_tblOrder] PRIMARY KEY CLUSTERED ( [OrderID] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]--------------------------------------------------------------------------------------------------------------------------------------------------------INSERT INTO tblProduct (Name) VALUES('Coffee')INSERT INTO tblProduct (Name) VALUES('Tea')INSERT INTO tblProduct (Name) VALUES('Lager')INSERT INTO tblOrder (ProductID, OrderDate) VALUES (1, '2013-01-01 09:00:00')INSERT INTO tblOrder (ProductID, OrderDate) VALUES (1, '2013-01-08 09:00:00')INSERT INTO tblOrder (ProductID, OrderDate) VALUES (2, '2013-01-08 09:00:00')INSERT INTO tblOrder (ProductID, OrderDate) VALUES (3, '2013-01-09 09:00:00')INSERT INTO tblOrder (ProductID, OrderDate) VALUES (1, '2013-01-10 09:00:00')INSERT INTO tblOrder (ProductID, OrderDate) VALUES (2, '2013-01-10 09:00:00')INSERT INTO tblOrder (ProductID, OrderDate) VALUES (3, '2013-01-11 09:00:00')INSERT INTO tblOrder (ProductID, OrderDate) VALUES (1, '2013-01-11 09:00:00')INSERT INTO tblOrder (ProductID, OrderDate) VALUES (2, '2013-01-15 09:00:00')INSERT INTO tblOrder (ProductID, OrderDate) VALUES (1, '2013-01-18 09:00:00')INSERT INTO tblOrder (ProductID, OrderDate) VALUES (1, '2013-01-30 09:00:00')INSERT INTO tblOrder (ProductID, OrderDate) VALUES (2, '2013-05-01 09:00:00')INSERT INTO tblOrder (ProductID, OrderDate) VALUES (3, '2013-07-15 09:00:00')INSERT INTO tblOrder (ProductID, OrderDate) VALUES (1, '2013-09-23 09:00:00')INSERT INTO tblOrder (ProductID, OrderDate) VALUES (1, '2013-10-01 09:00:00')INSERT INTO tblOrder (ProductID, OrderDate) VALUES (1, '2013-10-08 09:00:00')INSERT INTO tblOrder (ProductID, OrderDate) VALUES (2, '2013-10-11 09:00:00')INSERT INTO tblOrder (ProductID, OrderDate) VALUES (1, '2013-11-01 09:00:00')INSERT INTO tblOrder (ProductID, OrderDate) VALUES (3, '2013-11-06 09:00:00')INSERT INTO tblOrder (ProductID, OrderDate) VALUES (1, '2013-11-08 09:00:00')INSERT INTO tblOrder (ProductID, OrderDate) VALUES (3, '2013-12-10 09:00:00')INSERT INTO tblOrder (ProductID, OrderDate) VALUES (1, '2013-12-25 09:00:00')INSERT INTO tblOrder (ProductID, OrderDate) VALUES (2, '2013-12-30 09:00:00')INSERT INTO tblOrder (ProductID, OrderDate) VALUES (1, '2013-12-30 09:00:00')--------------------------------------------------------------------------------------------------------------------------------------------------------I need to generate report which shows number of orders for each ProductID for each week in year 2013. Ideally would be to generate 54 weeks as pivot table so week1, week2 would be columns and 3 rows for 3 products and order count for each product each week.Product

Performance Tuning

Posted: 17 Apr 2013 05:46 PM PDT

I have a Table called Employees with following Columns EmployeeID INT EmployeeName VARCHAR(256) Salary MONEY DeptID SMALLINT The table has following Indexes created on it 1. Clustered Index on EmployeeID 2. Non Clustered Index on EmployeeName 3. Non Clustered Index on DeptID The Employees tables has over 10 million rows. You want to get the count of Employees, for which you write the following query SELECT COUNT(*) FROM Employees What will be the likely query plan for above query? Which index will SQL SERVER use in above query? Please give an explanation for your answer.

In my laptop some times sqlserver getting problem while connecting in to the instance

Posted: 17 Apr 2013 06:07 PM PDT

HI all ,In my laptop some times sqlserver getting problem while connecting in to the instance 1. it is unable to connect the instance and iam checking the tcp/ip connections and all services but unable to connect in to the sqlserver 2. every time this happens i always uninstall the sqlserver and its services and freshly installing the sqlserver then it is working for few days or few months later it happens again but unable to solve this every time 3. iam checking these shared memory status enabled named pipes status enabled tcp/ip status enabled via status disabled windows firewall exception port number 1433 is added or not evry thing is working fine but it is unable to get connect in sqlserver [services are in not running during this period ] iam performing fresh instillation of the sqlserver How to avoid this and in which cases it happens if it happens in any server what should i do

HOW TO MAKE DYNAMIC PIVOT FOR THIS TABLES WHEN I PASS ONLY ONE PARAMETER @DID INT?

Posted: 16 Apr 2013 11:48 PM PDT

here iam having two table @DETAILS and @CONTACTDETAILS in this two table @DETAILS is a static table in which cotactid will be the primary key for the table @DETAILS and it will be the foreign key for the @CONTACTDETAILS and here this the tables with data[code="sql"]DECLARE @DETAILS TABLE (CONTACTID INT IDENTITY(1,1), VALUE VARCHAR(200))INSERT INTO @DETAILSSELECT 'PHONENUMBER' UNION ALLSELECT 'MOBILENUMBER' UNION ALLSELECT 'ADDRESS1' UNION ALLSELECT 'ADDRESS2' UNION ALLSELECT 'EMPLOYEENAME' UNION ALLSELECT 'EMPLOYEEID'DECLARE @CONTACTDETAILS TABLE (DETAILID INT IDENTITY(1,1), DID INT ,CONTACTID INT, DETAILSVALUE VARCHAR(200))INSERT INTO @CONTACTDETAILS SELECT 1,5,'SIVA' UNION ALL SELECT 1,6,'SIA001' UNION ALL SELECT 1,2,'9344139991' UNION ALL SELECT 2,1,'245678' UNION ALL SELECT 2,2,'1686597' UNION ALL SELECT 2,5,'GANESH' UNION ALL SELECT 1,3,'ST-ROAD' SELECT * FROM @DETAILSthe output for thisCONTACTID VALUE1 PHONENUMBER2 MOBILENUMBER3 ADDRESS14 ADDRESS25 EMPLOYEENAME6 EMPLOYEEID SELECT * FROM @CONTACTDETAILSthe output for thisDETAILID DID CONTACTID DETAILSVALUE1 1 6 SIVA2 1 5 SIA0013 1 2 93441399914 2 1 2456785 2 2 16865976 2 5 GANESH7 1 3 ST-ROAD[/code]in the @CONTACTDETAILS column iam having DID column which i used to show one particular employee detail in my stroe proc iam using parameter @DID int i just tried this query[code="sql"] declare @DID int=1 SELECT (SELECT VALUE FROM @DETAILS WHERE CONTACTID=A.CONTACTID)AS CONTACTID, A.DETAILSVALUE FROM @CONTACTDETAILS A WHERE A.DID=@DIDwhich will show the result like thisCONTACTID DETAILSVALUEEMPLOYEEID SIVAEMPLOYEENAME SIA001MOBILENUMBER 9344139991ADDRESS1 ST-ROADand now i am trying output like thisEMPLOYEEID EMPLOYEENAME MOBILENUMBER ADDRESS1 SIA001 SIVA 9344139991 ST-ROAD [/code] can any one plz help me

Error on SQL job - SQL 2008

Posted: 17 Apr 2013 10:54 AM PDT

Hi,Can someone help us to determine the resolution for the encountered error below.MessageExecuted as user: HO\sqlibg. The instance of the SQL Server Database Engine cannot obtain a LOCK resource at this time. Rerun your statement when there are fewer active users. Ask the database administrator to check the lock and memory configuration for this instance, or to check for long-running transactions. [SQLSTATE HY000] (Error 1204). The step failed.Actions Taken:1. Enabled AWE.2. Input number of locks to 10K3. Checked blocking sessions - none

PBM(Policy Based Management) Implementation issues

Posted: 17 Apr 2013 05:12 PM PDT

HiMy policies just noticed that Public has the 4 default Connect permissions on endpoints. To get rid of them I would be using the beloe commands :REVOKE VIEW ANY DATABASE FROM public;REVOKE CONNECT ON ENDPOINT::[TSQL Local Machine] FROM public;REVOKE CONNECT ON ENDPOINT::[TSQL Named Pipes] FROM public;REVOKE CONNECT ON ENDPOINT::[TSQL Default TCP] FROM public;REVOKE CONNECT ON ENDPOINT::[TSQL Default VIA] FROM public;However, before I do that I need to provide connect permissions on All TCP ports to other logins so that they are not thrown out. Here, I am facing issues while providing grant to the following logins :--GRANT CONNECT ON ENDPOINT::[TSQL Default TCP] TO [##MS_SQLAuthenticatorCertificate##] --GRANT CONNECT ON ENDPOINT::[TSQL Default TCP] TO [##MS_SQLReplicationSigningCertificate##] --GRANT CONNECT ON ENDPOINT::[TSQL Default TCP] TO [##MS_SQLResourceSigningCertificate##] Error for them says :Cannot find the login '##MS_SQLAuthenticatorCertificate##', because it does not exist or you do not have permission.My questions here are :1. If I am unable to grant connect to these logins, will it have adverse affects on some operations?2. Any other impact that is usually reported after the Public has been revoked the default access?will someone please assist me with the clarifications ?Thanks in Advance..

xp_cmdshell slow response

Posted: 17 Apr 2013 04:31 PM PDT

I am using xp_cmdshell to bcp out a small table to a file and than copy it inside the local disk.1. The system (memory , cpu , disk queue) are all not loaded with work.2. The table is very small and the bcp results in 1 KB file.3. The bcp operation varies under the xp_cmdshell between 700ms to 2200 ms .4 Using cmd prompt from the windows os the same operation of bcp takes 31 ms. (login are the same as sql service)5. The xp_cmdshell operates fast on another server.6. The same operation performed 2 weeks ago worked fast on this server.Somthing had changed but what to look for ?:hehe:

How to know the original user name

Posted: 17 Apr 2013 10:42 AM PDT

Hi all,I'm having hard time to figure out a way to create a DDL trigger while capturing the original user name who initiated a connection. ASP.NET application is running on IIS server and AppPool is configured with a shared account to make a connection to SQL. So, from the SQL server side we only see this shared account.My problem is, how to know who actually initiated the connection originally. ORIGINAL_LOGIN() won't work since IIS is using a shared account so wonder if there's a way from SQL side. Anyone knows if this is even possible? I don't think it is but wonder if there's a way, hope...Thanks~

DBCC on a detached MDF file

Posted: 10 Apr 2013 07:05 AM PDT

Hello,I am by no means above a SQL novice, but I am trying to figure out if there is a way to run DBCC commands (DBCC fileheader in particular) on an offline/detached MDF? Is this possible? If so, any help pointing me in the right direction? Thank you!

Creating array in sql server

Posted: 16 Apr 2013 09:05 PM PDT

A string contains 3,4 suppose I want to store 3 in one parameter and 4 in another parameter similar in c# like arr[0] and arr[1]? how can i achieve it

read values in column from xlsx files in SSIS

Posted: 17 Apr 2013 02:31 AM PDT

is it possible to write a code that will read the values in a specific column from xlsx files in SSIS? i'm comfortable with visual basic 2008.in a_square.xlsx, there's a column named "country"and in b_a_circle.xlsx, there's a column named "country_region"i want it to read the values in country in a_square.xlsx and also read the values in country_region in b_a_circle.xlsx so it'll create a new file if there's a match (for example, if the country has a US value in it and the country_region has a US value in it as well)sorry i know this sounds too confusing but i don't know how to explain it better.

[Microsoft][ODBC SQL Server Driver][SQL Server]1

Posted: 24 Jun 2010 05:05 AM PDT

I am using a basic script that calls an ODBC connection on the computer to write records to our SQL 2008 database. It will write three records, return this message [Microsoft][ODBC SQL Server Driver][SQL Server]1 and then it will continue to write the next three records. This is a problem because I only get six of the seven records. I know that this message is returned because I write the information into a text file.Could this message be a connection problem between the computer and the server? I haven't seen anything online like it yet. Is there a place on the server that might tell me more information so I can better diagnose this problem?

Large Object in buffer cache

Posted: 17 Apr 2013 12:59 AM PDT

HelloWe are using Redgates SQL Monitor tool and I am getting 'Large object in buffer cache' alert message - I have read that I need to find out what the object is and that this object may be suitable for compression or a schema revision (data type changes or sparse columns).I have ran the following query:USE [tempdb]GOSELECT COUNT(*) AS cached_pages_count , ( COUNT(*) * 8.0) / 1024 AS MB , CASE database_id WHEN 32767 THEN 'ResourceDb' ELSE DB_NAME(database_id) END AS Database_name FROM sys.dm_os_buffer_descriptors GROUP BY DB_NAME(database_id) , database_id ORDER BY cached_pages_count DESC;and the results are thus :Cached_pages_count MB DataBase_Name344695 2692.929687 a336681 2630.320312 b320527 2504.117187 c154540 1207.343750 dCan anybody advise on how i deal with the alert

Trigger issue, help with trigger

Posted: 17 Apr 2013 04:30 AM PDT

I have a SQL2008R2 db that has a regular table and an audit table. I have a trigger setup so it will keep track of changes via an audit table. When an update statement is run against the regular table it fails with:Msg 2627, Level 14, State 1, Procedure TI_JOB_POSTING_TRIGGER, Line 15Violation of PRIMARY KEY constraint 'PK_JOB_POSTING_AUDIT_1'. Cannot insert duplicate key in object 'dbo.JOB_POSTING_AUDIT'. The duplicate key value is (548, 0589054 , Apr 17 2013 12:37PM).THis is the statement run against the table: update job_posting set site_num=8800Here is the regular table:[dbo].[JOB_POSTING]( [JOB_POSTING_NUM] [int] IDENTITY(1,1) NOT NULL, [SITE_NUM] [int] NULL, [JOB_CAT_COD] [varchar](7) NOT NULL, [DEFAULT_TXT_IND] [bit] NOT NULL, [ADDRESS1_TXT] [varchar](100) NULL, [ADDRESS2_TXT] [varchar](100) NULL, [CITY_NAM] [varchar](50) NULL, [ST_PROV_COD] [char](2) NULL, [POSTAL_COD] [varchar](10) NULL, [START_DAT] [date] NULL, [END_DAT] [date] NULL, [MAINT_EMP_ID] [char](11) NOT NULL, [MAINT_TMS] [datetime] NOT NULL, [UPLOAD_TMS] [datetime] NULL, [POST_IND] [bit] NULL, [COMBINATION_NUM] [int] NOT NULL, [CREATE_EMP_ID] [char](11) NOT NULL, [CREATE_TMS] [datetime] NOT NULL, CONSTRAINT [PK_JOB_POSTING] PRIMARY KEY CLUSTERED ( [JOB_POSTING_NUM] ASCHere is the trigger:ALTER TRIGGER [dbo].[TI_JOB_POSTING_TRIGGER] on [dbo].[JOB_POSTING] for INSERT, UPDATE AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; Insert into job_posting_audit (JOB_POSTING_NUM ,SITE_NUM ,JOB_CAT_COD ,DEFAULT_TXT_IND ,ADDRESS1_TXT ,ADDRESS2_TXT ,CITY_NAM ,ST_PROV_COD ,POSTAL_COD ,START_DAT ,END_DAT ,MAINT_EMP_ID ,MAINT_TMS ,UPLOAD_TMS ,POST_IND ,COMBINATION_NUM) SELECT JOB_POSTING_NUM ,SITE_NUM ,JOB_CAT_COD ,DEFAULT_TXT_IND ,ADDRESS1_TXT ,ADDRESS2_TXT ,CITY_NAM ,ST_PROV_COD ,POSTAL_COD ,START_DAT ,END_DAT ,MAINT_EMP_ID ,MAINT_TMS ,UPLOAD_TMS ,POST_IND ,COMBINATION_NUM FROM insertedENDThis is my first go around with triggers... what am I doing wrong?

Number of Active Users

Posted: 17 Apr 2013 06:11 AM PDT

1)find number of users on a database in sql server 20122)find number of users accessing in sql server 20123)find users using a specific object on a database inn sql server 20124) active process in sql serverCan someone provide me how to find above for SA on the server and a user who has db_reader role on serverThanks a lot in advance

join aggregated quantity to the breakdown quantity

Posted: 17 Apr 2013 01:58 AM PDT

I have two tables, one with (potentially) multiple records of an item with different quantities, and the other table will have only one record for each item and will aggregate the sum total of the quantities - i.e.:Table 1 Item Qty MemoABC 24 pending Table2 Item Qty MemoABC 14 testABC 10 testXYZ 5 testI need to update the memo in Table1 with the memo from Table2, and would like to find an efficient way to do so. Any advice would be greatly appreciated.

CMDExec Proxy account not working with Domain Service Account...

Posted: 17 Apr 2013 12:17 AM PDT

I'm working on migrating an existing Server 2003 / SQL 2005 system to Server 2008 R2 / SQL 2008 R2, and am having some problems getting a proxy account to work. The account is needed to execute some OS operations, NOT to affect DBs on the server. Things like unzipping files that are recieved to a particular folder and deleting the files when done.The SQL Agent is running using a domain account for this purpose. There's also a domain-level account for the proxy account.I've added the Proxy account to the SQL Logins, created a Credential for it, then created the Proxy in Agent. I've granted the appropriate users access to the Proxy (the "Principals" section), and assigned the proxy to execute a step in a test job (dir e:\)Now, the problem.It fails.If I run the step using the Agent account, it works. If I set the Agent to use the "Network Service" account and the proxy, it works. If I set the Agent to use the domain account and the job to use the proxy account, it fails with:"Executed as user: domain\svcaccount. The process could not be created for step 1 of job 0x2E0030DE6B7C444E8C0E4759A405B8E5 (reason: A required privilege is not held by the client). The step failed"I have verified the proxy account does have access to the E:\ drive by running a command prompt as the account. I also "cloned" the local group membership for the proxy from the Server 2003 system, so it belongs to the local Admins account.I've looked through the Windows Security log, and it shows it to be logging in OK. I see a logon event with a subject account name of the Agent service account, and a new logon security ID of the Proxy account. So it seems the impersonation is working...Any thoughts?

Ghost Cleanup and CHECKPOINT after Migration to SQL 2008 R2

Posted: 17 Apr 2013 05:48 AM PDT

I am migrating a database from SQL 2005 to SQL 2008 R2. As soon as the database is restored over to the new server with SQL Server 2008 R2 enterprise, it starts Ghost Cleanup and CHECKPOINT process. It takes about an hour and disks are pegged, utilization is very high during this one hour. It doesn't even let me open database property and simple queries on this database takes forever or times out.New server has a much better and the best possible hardware. Database size is 600 GB. There were lot of data deleted on the old server few months back. LDF file is 1 GB when restore completes but then it starts going up as big as to 60 GB. When I run sys.dm_db_index_physical_stats on the database, it doesn't give me HUGE number of ghost_record_count as well. Out of 500 tables in the database only one table has 300 ghost record count and few other tables have 1 or 2. Is it deleting those records after migration? Is it because Ghost cleanup doesnt currently run on my SQL 2005 box?Any suggestions?

Substract End Dates

Posted: 16 Apr 2013 09:11 PM PDT

Hi Professional I need to substract the end date as like below2-1,3-2,4-3, and showing in new column like datediif_days if there would be null we have to treat as gatedate.[code="sql"]CREATE TABLE abc(gg_key int,fg_sta_key int,fg_eff_dt_key int,fg_end_dt_key int,fg_seq_nbr int)[/code][code="sql"]insert into abc values(19925,2,20130128,20130128,1)insert into abc values (19925,8,20130128,20130128,2)insert into abc values(19925,1,20130129,20130416,3)insert into abc values (19925,5,20130417,NULL,4)[/code]Regards,KiranR

Pros & Cons- Table Value Function vs Summary Table

Posted: 17 Apr 2013 01:07 AM PDT

For discussion...I need to provide summary information on records in a table such as total amounts of varying types and total amounts by status. An example would be total amount of transactions pending, total amount of transactions accepted, etc. This would be across all accounts, but also at the account level so toss in there total amount of transactions pending by account.In the past, I would go with a summary table however I'm not in a position to chase that rabbit so my thought was to do a Table Value Function that queries the table once, and then generates the totals using a Table variable.The number of users on the front end website is very minimal (3) so the added cost of performing the calculations in memory shouldn't have that great of an impact.

AD name change Old name still persists

Posted: 16 Apr 2013 11:36 PM PDT

After a user change of name in AD. SQl still shows the user as the previous credentialsIe Domain\UsernameoldDomain\UsernamenewAlthough the users name has changed to the new account the old one still persists in SQL.Domain\Usernameold no longer exists as it cannot be added to a test server as a domain login.SQL must be caching the credentials and marrying them up with the SIDs. How to remove this from the cache.

Transactional Replication with updatable subscribers over the internet

Posted: 16 Apr 2013 11:44 PM PDT

I have created a publisher on server A. I need to create a subscriber on server B over the internet. For this i'm using VPN. While creating subcriber I get following message: "the initial snapshot for publication is not yet available". I suppose this is because of some permission issue to the snapshot folder which I have created on Server A. Do I need to have same windows authentication on both servers? As of now they are different as my servers are on different domains. Please help.

Compare scripts B4 and After a Performance Fix !

Posted: 16 Apr 2013 11:09 PM PDT

"How can I"/"what are all the ways I can" compare a query/SP before and after a Performance Fix, to know whether Am I improved it really. in case of speed, memory, resource and what else..Appreciating your helps always,Rafi

Third party backup tool breaking the backupset LSN chain

Posted: 23 Mar 2011 09:48 AM PDT

I am attempting to develop a workaround to this issue and was wondering if it is possible to modify the BACKUPSET lSN numbering of a backup so as to skip the piece or pieces of the backup completed by the third party tool so the next transaction log backup starts at the lsn numbering of the backup before the third party tool was run.

configuring alerts

Posted: 16 Apr 2013 08:46 PM PDT

Any one help how to configure alerts on sql like log growth , backup failure ,disk space . login failed etc as part of daily activity while monitoring server?

how to do pivot

Posted: 16 Apr 2013 07:42 PM PDT

Hi Guys,actually my table data looks Key valuefirstname suryafirstname rakhifirstname venkatfirstname shankarfirstname danyI want to disply likefirstnamesuryarakhivenkatshankardanyi write the below querySELECT firstnameFROM test pvtPIVOT (MAX(pvt.value ) FOR pvt.key1 IN (firstname)) AS Pbut it showingfirstnamevenkatPlease help to solve this

Search This Blog