Tuesday, April 16, 2013

[SQL Server Data Warehousing] Need some clarifications on Sql Server 2012 QA & Prod environment setup


I think the original question requested information on Licensing as well, which none of the answers contain. I agree on the HW configuration part - they majorly depend on application size including data volume.


With SQL Server 2012 we can use Standard (Core / Server-CAL), BI (Server-CAL) and Enterprise (Core) editions, - among them which edition to choose will depend on what features the solution needs. On high level, if the solution needs canned reporting on moderate sized data, Standard edition will do. If it requires ad-hoc / self-service BI then we need BI or Enterprise edition. If the data volume is high requiring columnstore indexing, we need Enterprise edition.


So far so good, all these are options for the Prod environment.


But for Dev and QA, can we use Developer edition license:


1. Will that license be able to access data from some other SQL Server database (which might be copy of Prod data for Dev and QA)


2. Will that license enable us to move SSIS/RS/AS/PowerView codes to Prod environment without any issues? 


Can some expert from Microsoft answer this question - which I think would answer a good part of the original question as well.



Souvik Banerjee. MSBI Lead, Zensar Technologies



.

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

[Articles] Don't Be a Ghost

[Articles] Don't Be a Ghost


Don't Be a Ghost

Posted: 15 Apr 2013 11:00 PM PDT

If you want to further your career, you can't be a ghost. Steve Jones talks about the ways in which so many people might end up hurting their careers by trying to keep their lives too private.

[MS SQL Server] [Bulk Insert] Performance issues

[MS SQL Server] [Bulk Insert] Performance issues


[Bulk Insert] Performance issues

Posted: 16 Apr 2013 04:39 AM PDT

Hello all,I'm facing a serious performance issue on my SQL Server 2008 database.Let me give you my scenario.I have a database with almost 4 TB of data. Only one table has 1,5 TB of space. This table is partitioned and have, including the clustered index, 5 indexes. This table is partitioned by a DATETIME column, with 3 hours of data in each partition.This table is constantly populated via BULK INSERT and that's where the problem is. The number of files to be inserted through BULK INSERT keeps increasing and the database doesn't keep the same pace, it's always delayed.I tried to do several tests: changed the recovery model, increased the BATCHSIZE, adjusted the ORDER clause. No success.My question: is it possible to disable a particular index partition, do the BULK INSERT and, then, REBUILD the specific "broken" partition? I don't want to disable the whole index, because there are data that are constantly accessed and all of those indexes are used. We studied all those indexes and removed some unused ones and optimized the remains.Can anyone shed a light over this?Thanks

Linked server questions

Posted: 16 Apr 2013 04:52 AM PDT

Hello, all - I am trying to understand linked servers and trying to find a couple of answers.We have a server named like server1\server. I'm trying to create a link to this server from another one called (for the example) server2. The link appears to have worked, but when I look at the catalog, there's nothing there but "default" and "system." How do I get all the db catalogs to appear? And is there anything wonky because of the "server1\server" name? I'm pretty sure it needs to have both parts, because I could not get this to work/connect using just "server1."I'm not getting any error messages, I'm just not seeing the db's/catalogs I expect to see. I've tried looking at other linked servers, but of course, they're all on server1/server, so I don't have any good examples of a linked server coming in.Any information would be greatly appreciate - thank you!

Small doubt

Posted: 15 Apr 2013 03:11 PM PDT

Here i have some doubts 1) what is the difference between current execution plan and actual execution plan2) on which parameter based we can find it

Error while I connecting oracle database in SSIS connections issues

Posted: 16 Apr 2013 12:06 AM PDT

TITLE: Connection Manager------------------------------Test connection failed because of an error in initializing provider. ORA-12154: TNS:could not resolve the connect identifier specified------------------------------BUTTONS:OK------------------------------

Commvault Simpana 9 SQL Backups

Posted: 24 Oct 2011 10:01 PM PDT

Hi,We have an ongoing battle with our Infrastructure Architect, where they would like to incorporate all SQL Backups in the same solution as the server and filesystem backups which uses Commvault Simpana 9.Our current SQL backups are backed up by the native SQL backups, and then bak file backups taken by Commvault.In the past we attempted to use Commvault 7 with both SQL and Oracle, however this was a nightmare experience where servers ground to a halt, and restores would fail. I am being reassured that the newest versions is a lot better and we would not experience the same issues.I along with the Oracle DBA's are very skeptical by this statement due to past issues, and in our experience have found no 3rd party app that better backsup SQL/Oracle than the inbuilt tools.Has anyone had expereince of using Commvault Simpana 9, and can offer any feedback on experiences?Thanks

Transactional Replication

Posted: 15 Apr 2013 06:47 PM PDT

What are the permission required to configure Transactional Replication? :-P

BackupExec SQL Agent or SQL Server Native backups????

Posted: 06 Jan 2013 11:27 PM PST

I'm looking after a whole bunch of SQL Servers, both 2005 and 2008, some full and some simple recovery databases with the largest database at 126Gb and some others over 30Gb. Current backup strategy which I've set up is nightly full backups (using sql agent and native SQL Server backups) to disk with transaction log backups at intervals during the day (frequency depends on the application). After each full or log backup the backup file is copied to a fileshare on another physical server and both the SQL server and the backup fileshare are copied to tape nightly using BackupExec but only copying the backup files not letting it do its own agent backup. There is a proposal afoot to have BackupExec do all the backups with its agent (which they've already bought) straight to tape and not do any SQL Server native backups. This is to reduce the disk space used. I'm not at all keen on this but am trying to find up-to-date arguments to justify my position. I've read the previous discussion on this forum but that was nearly four years ago and things change so what does the forum think?One downer I've read is that BackupExec would not support restoring to drive letters that were different from the original backup location - as I regularly restore live to test or to copy databases elsewhere this is important to us. Is it still true with current versions?Also if a database is added to the SQL Server does BackupExec automatically pick it up and back it up or does it have to be added to the job by someone? Since I use Ola Hallengren's backup routine in many cases, the native backup routine picks up most new databases:-)I'm very happy with the status quo but need to argue to keep it. Please could you help me collect the justification?

Shrinking Database or File not Reclaiming unused space

Posted: 15 Apr 2013 12:54 PM PDT

Hello,First time poster, long time lurker. I thought this was an interesting enough question to ask.Pretty often we bring our clients databases (we sell software which backs onto an SQL server database) back in house to cut into test environments. Something we do to these databases is drop all the BLOB data so we're not dealing with several hundred GB of essentially useless data. We just don't need it for testing and dev work. I've carried out the following steps and have tried to shrink the data file and database without getting any space reclaimed. I'm wondering why this is happening and would like to figure out a way to reclaim the space without having to backup and restore the database. Any advice or thoughts would be welcome, this strikes me as a bit of an oddity and I'm sure there's a good reason for the behavior buried under the hood somewhere.-Switched to simple recovery mode (to avoid log bloat, maybe pointless when dropping the column?)-Dropped stats on blob columns-Dropped Blob Columns-Rebuilt indexes on the tables containing the blobs-Recreated the blob columns-Switched back to full recovery mode-Attempted file shrink on data file (no change in size)-Attempted database shrink (no change in size)

New features in sql server

Posted: 15 Apr 2013 03:34 PM PDT

What are the new features available in sql server 2008 and 2012

How to check performance issue

Posted: 15 Apr 2013 03:17 PM PDT

query execution is taking long time here how to solve thisfor this type of performance issueswhat is the necessary steps to solve this issue Please provide the step by step process

[SQL 2012] PK Lookup Doing Table Scan?

[SQL 2012] PK Lookup Doing Table Scan?


PK Lookup Doing Table Scan?

Posted: 16 Apr 2013 02:06 AM PDT

I had an issue with replication that I posted in the replication forum, but I don't think it is specific to replication as much as SQL2012 and indexing issues. Here is the other post, not sure if anyone in this forum has experienced this before?[url]http://www.sqlservercentral.com/Forums/Topic1442423-291-1.aspx[/url]Basically, the merge process that enumerated changes in batches (sp_MSenumchanges_belongtopartition) executed a query to join the rowguid of the changes to the PK/rowguid in my user table. This should have been a super fast query to seek the clustered index of my user table, but instead looking up a 100 row batch was taking around 10 minutes (sometimes significantly longer) and pinning the CPU. If I ran the same query manually, outside of sp_MSenumchanges_belongtopartition, it would return in a matter of milliseconds.Index usage stats looked like sp_MSenumchanges_belongtopartition was executing a scan on the table, instead of doing a clustered index seek like it would if I executed the query manually. I have no idea why the SP would be executed such a bad query plan, and not sure how to confirm that was the issue or how to more-permanently resolve it?For now, I created a second nonclustered index on the PK, effectively duplicating the clustered index. Now replication is fine and sp_MSenumchanges_belongtopartition executes in <1s. When I look at the query plan, it shows sp_MSenumchanges_belongtopartition using my new index to locate the PK of the row. Then it joins that result to a clustered index seek to pull the whole row of data. So it's not as efficient as just a clustered index seek, but is working.Any ideas? Index corruption a possibility? What should I look at next?

SQL Query - Actual performance duration for every execution

Posted: 15 Apr 2013 10:14 PM PDT

Hi,I have a SQL query with couple of nested queries (query at the bottom for the reference), now the very first time I execute the query on a SQL Server instance, it takes around 50-60 seconds to execute, but there on for every consecutive execution, it barely takes 1 second and I am baffled, because I want it to take its original time for me to do anything about reduction of its original execution time. I want to try various tuning and query modification aspects.I have tried clearing all caches using the commands listed underneath, but they does not help in getting the original execution time.We are using "SQL Server 2012 Enterprise Edition"use <Database_Name>GOCHECKPOINT; GO DBCC FLUSHPROCINDB(<Database_ID>)DBCC FREEPROCCACHEDBCC DROPCLEANBUFFERSDBCC FREESYSTEMCACHE ('ALL')DBCC FREESESSIONCACHEGONormally anyone would be happy that query is performing great after first execution but my aim is different, I want it to take actual time for every consecutive executionPlease help me to resolve the issue mentioned above, any pointer would be great, please let me know if you need more detailsthanks,MrinalQuery Text for Reference=======================SELECT OprtngOrigHandlingNodeID, OprtngDestHandlingNodeID, ShpmtOrigHandlingNodeID, ShpmtDestHandlingNodeID, CAST(COUNT(*) as real)/ (SELECT ABS(DATEDIFF(d,'2013-02-01','2013-02-28'))+1 as DaysInRange) AS carsFROM ( select distinct S.* from RBIS_UI.Trip_Plan TP, RBIS_UI.combined_shipments S, ( SELECT * FROM ( SELECT T.TrainRunID, T.Rundate, T.TrainRunCode, T.Distance, T.Speed, T.Cars, T.InterModal, T.Length, T.Weight, T.WorkStops, T.NonDesignStops, T.HP, T.HPTT, T.ActLocoCount, T.DeactLocoCount, T.TotalLocoCount, T.DepDesignTimeDiff, T.ArrDesignTimeDiff, T.TransitTime, T.DesignTransitTime, T.LocalArrtime AS Arrtime, T.LocalDeptime AS Deptime, T.LocalDepSchedTime as DepSchedTime, T.LocalArrSchedTime as ArrSchedTime, T.DepDelay, T.ArrDelay, T.titanID, T.tyesID, T.CorCapacity, COALESCE (dt_TrainName, trainname) as trainname, COALESCE (dt_OpsTypeId, OpsTypeID) as OpsTypeID, COALESCE (dt_BizType, BizType) as BizType, COALESCE (dt_ActualOrigHandlingNodeID, ActualOrigHandlingNodeID) as ActualOrigHandlingNodeID, COALESCE (dt_ActualDestHandlingNodeID, ActualDestHandlingNodeID) as ActualDestHandlingNodeID, ActualOrigHandlingNodeID as Actual_ActualOrigHandlingNodeID, ActualDestHandlingNodeID as Actual_ActualDestHandlingNodeID, DesignOrigHandlingNodeID, DesignDestHandlingNodeID, OpsTypeID as Actual_OpsTypeID, BizType as Actual_BizType, TrainName as Actual_TrainName, T.DesigntrainID, DETOURFLAG, Via, CarsLoaded, IntermodalLoaded, CarsEmpty, IntermodalEmpty, Addition -- , -- DepDesignTimeDiff, --ArrDesignTimeDiff FROM ( SELECT * FROM ( SELECT * FROM RBIS_UI.train_runs WHERE RunDate BETWEEN '2013-02-01' AND '2013-02-28') FT WHERE OpsTypeID IN ( 1,2,3,5,6,9 ) ) T) TR WHERE ((TR.TrainName = '470')) AND ((TR.ActualOrigHandlingNodeID = 1190)) AND ((TR.ActualDestHandlingNodeID = 504)) AND ((TR.DesignTrainID = 1901)) AND ((TR.OpsTypeID = 3)) AND ((TR.BizType = 'SECO'))) TR where TR.TrainRunID = TP.TrainRunID and TP.CSN = S.CycleSerialID and TP.Shipment_ReleaseDate = S.ReleaseDate AND TP.EqpmtType <> 2 ) FSGROUP BY GROUPING SETS ( (OprtngOrigHandlingNodeID), (OprtngDestHandlingNodeID), (ShpmtOrigHandlingNodeID), (ShpmtDestHandlingNodeID) )

SQL 2012 AG/FCI Failover

Posted: 15 Apr 2013 06:43 PM PDT

Hi AllMy Setup:>> 3 Servers (Node1-Node2-Node3) all part of the same Cluster "Cluster1">> SQL installed as clustered on Node2 & Node3, producing "SQLCluster">> SQL installed as nonclustered on Node1, producing "Node1\SQL">> Availability Group has been set up between "SQLCluster" & "Node1\SQL"Quorum: What is the recommended Quorum configuration for my setup, I'm assuming Node majority.DTC: Should all the nodes be a possible owner of DTC? Should the DTC disk be presented to all the nodes?Failover: When configuring the failover mode, I am unable to change it to Automatic, is Automatic failover not supported when you combine an AG with an FCI or am I missing something?Thanks

Problem SSIS 2012 using Teradata Destination

Posted: 15 Apr 2013 07:39 PM PDT

Hi,I installed Attunity SSIS Terdata Adapter Version 2.0 on my machine (SQL Server 2012 EE), downloaded from the Microsoft page.I tried just an easy File Connection reading a CSV File to import it into a Teradata (14.03) using the Teradata Destination component. The error "[b]The Teradata TPT registry key cannot be opened. Verify that the TPT API 12.0 or 13.0 Edition 2 (13.0.0.2) for Windows x86 is installed properly." [/b]was thrown by SSIS.I have installed the TPT 14.00 on my machine, and the version 2.0 of the Teradata Destination should work with TPT 14.00 and SQL Server 2012 (EE)?!Does anyone has an idea how to solve that?Thanks in advanceHelmut

Cannot connect using mixed authentication

Posted: 15 Apr 2013 12:53 PM PDT

We are attempting to deploy a SQL Server Express 2012 application in a network using Workgroup networking, and as a result are having to use SQL Server logins rather than Integrated security. All works as it should when connected to the PC running SQL Server. However when we attempt to connect from another Win7 workstation using ODBC, we either get timeout errors, or we get the message that SQL Server actively rejected our connection attempt (we are using Native Client 11 as the ODBC driver, both on the SQL Server PC, and on the network PC). We are also getting Error 8 - "The SQL Server Browser service was unable to process a client request" logged in the Application Log on the SQL Server PC in some attempts, but not in others. Any suggestions on what might be causing the problem? We've done this sort of configuration previously using SQL Server Express 2008 and gotten it to work, but we been banging our heads on this for 3 weeks now, and exhausted all of our usual bag of tricks. Thanks in advance.Wendell

SQL Server Port Number Assignments - How To Determine What Number To Use

Posted: 15 Apr 2013 06:57 AM PDT

Google "SQL Server Static Ports" or any variation of it and you'll get a hundreads of thousands or more pages full of links and everyone will provind emost of what you need. If you query is instead "How to Determine WHAT Port Number TO use" then forget about it, you get nothing. I've found more articles then I can count on how to change SQL Server from dynamic port to fixed ports but not one on how to determine what port number to assign. I know there are lists of port numbers used by certain apps and services but that still doesn;t help me to deterine what poirt numbers I can or even should use for SQL Server. Do I just randomly piece together a set of 6 dgits or do I need to select from a specifi range and if yes what range and how do I detemrine if a port number is OK to use?Perhaps this ia dumb question that everyone knows but me and thats why theres no hits for this query?We're setting up Syetm Center 2012 and we have no choice but to go with Static ports. Does anyone have any suggestions on how I go about dertermining what post number(s) I can use/try?Thanks

[T-SQL] Storing Spatial Data

[T-SQL] Storing Spatial Data


Storing Spatial Data

Posted: 15 Apr 2013 06:57 PM PDT

Hi All,I work with geospatial specialists who provides me with polygons which i save it to my geography field. And any spatial related queries are queried to this field and i get the values as well. The polygon details are provided as a string of lat and long pairs. For eg (Lat1 Long1, Lat2 Long2,.......Lat1 Long1)as my first point and last point needs to be same for a polygon.I have read in many blogs that we need to provide a point as Long Lat and not as Lat long. That is, we recieve the points as Lat Long but we need to reverse the points as Long LatSo my ploygon value before converting to Geography data type, i reverse the points. The string will be (Long1 Lat1, Long2 Lat2,........Long1 Lat1)This works fine for me and my queries are fetching the values properly. Now we have another feature added to the web application wherein the geospatial team would draw a polygon on the google map. When a polygon is drawn, google map API gives me the points of the polygon. We can plot as many points and the user ensures that the polygon ends at the same location where it started. The API provides me the points in Lat long pair. However it gives only distinct points. So what i do is that i take the first point and add at the last to ensure that i dont get an error when i convert it into a geography data. But even then i get[b] "The specified input does not represent a valid geography instance"[/b] error.INSERT INTO SpatialTable (GeogCordinate)VALUES (geography::STGeomFromText('POLYGON((76.9410753250122 11.05135492884294,76.94399356842041 11.055229898350953, 76.95734024047851 11.053439837277391,76.96186780929565 11.045963581774801,76.94744825363159 11.044805271627415,76.93420886993408 11.048764567419667, 76.9410753250122 11.05135492884294))', 4326));If i do not reverse my Lat and Long value in a pair and if my query isINSERT INTO SpatialTable (GeogCordinate)VALUES (geography::STGeomFromText('POLYGON((11.05135492884294 76.9410753250122,11.055229898350953 76.94399356842041,11.053439837277391 76.95734024047851,11.045963581774801 76.96186780929565,11.044805271627415 76.94744825363159,11.048764567419667 76.93420886993408,11.05135492884294 76.9410753250122))', 4326));then it works. I am confused if i need on how to pair the Lat and long value before converting it into a geograpahy data type.Any help is highly appreciated. Thanks & RegardsKrishna Kumar. P

Need to call a table as a variable

Posted: 16 Apr 2013 02:44 AM PDT

I need to pull records from a table and that would be pretty simple, however, the select statement needs to run as a sproc that passes a variable input as the table name. Let me illustrate:create procedure dbo.sproc(@tablename varchar(10))AsSelect cust#, fname, lname... other fieldsFrom tableAWhere Cust# in (Select Cust# from @Tablename)the error is telling to declare the table variable, but if I declare it as table I have to include the fields and I dont want to. Does this work better with dynamic SQL? What's the best way to do this?

Wildcard DB name in VIEW of Procedure - Possible?

Posted: 16 Apr 2013 02:31 AM PDT

Hi there,I've been trying to figure out whether it's possible to have a Wildcard DB name in a SELECT query. eg. Database1, Database2, Database3, Database4, Database5, Database6 all have the same schema - but for different aspects of the business.What I would like to figure out to do is to run something like this:SELECT Col1, Col2, Col3, Col4, Col5 FROM AllDatabases (where AllDatabases is a concatenation of Database1-6)At the moment, the best solution i've come up with is to loop round all the DB's and place the results into a temporary table, then select the results from the temporary table.HOWEVER - the list of DB's *could* change. Not often, but it's possible. Ideally it needs to be as dynamic as possible.Am I barking up the wrong tree here, or should I just stick with the looped concatenation of the DB's ?Dave

Group of Groups

Posted: 15 Apr 2013 03:11 AM PDT

Hello All,Thanks if you would like to help.I am hoping there is a 'best practice' way to solve this problem but searching 'sql server groups' gets a lot of results.I have two tables, groups and group members. My goal is to write a function that when passed a group code will return all the group members.The complicating factor is when a group contains other groups. I'd like to allow for multiple levels of groups.I am certainly open to revising my table structures at this point. I expect dozens of groups and thousands of group members. I also have a Members table (not shown) if that helps.Passing C should get the members 1,2,3,4Passing D should get 4,1,2Passing E should get 1,2,3,4,5IF OBJECT_ID('[dbo].[GroupMembers]') IS NOT NULL DROP TABLE [dbo].[GroupMembers]IF OBJECT_ID('[dbo].[Groups]') IS NOT NULL DROP TABLE [dbo].[Groups]CREATE TABLE [dbo].[Groups]( [GroupCode] [varchar](20) NOT NULL, [GroupDescription] [varchar](20) NULL CONSTRAINT [PK_Groups] PRIMARY KEY CLUSTERED ([GroupCode] ASC)) CREATE TABLE [dbo].[GroupMembers]( [GroupCode] [varchar](20) NOT NULL, [Member] [varchar](20) NOT NULL, [MemberType] [varchar](12) NOT NULL CONSTRAINT [PK_GroupMembers] PRIMARY KEY CLUSTERED ( [GroupCode] ASC, [Member] ASC, [MemberType] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]GOALTER TABLE [dbo].[GroupMembers] WITH CHECK ADD CONSTRAINT [FK_GroupMembers_Groups] FOREIGN KEY([GroupCode])REFERENCES [dbo].[Groups] ([GroupCode])GOINSERT INTO Groups (GroupCode,GroupDescription) VALUES ('A','Simple group')INSERT INTO Groups (GroupCode,GroupDescription) VALUES ('B','Simple group')INSERT INTO Groups (GroupCode,GroupDescription) VALUES ('C','Group of Groups')INSERT INTO Groups (GroupCode,GroupDescription) VALUES ('D','Mixed')INSERT INTO Groups (GroupCode,GroupDescription) VALUES ('E','Complicated')INSERT INTO GroupMembers (GroupCode,Member,MemberType) VALUES ('A','1','Individual')INSERT INTO GroupMembers (GroupCode,Member,MemberType) VALUES ('A','2','Individual')INSERT INTO GroupMembers (GroupCode,Member,MemberType) VALUES ('B','3','Individual')INSERT INTO GroupMembers (GroupCode,Member,MemberType) VALUES ('B','4','Individual')INSERT INTO GroupMembers (GroupCode,Member,MemberType) VALUES ('C','A','Group')INSERT INTO GroupMembers (GroupCode,Member,MemberType) VALUES ('C','B','Group')INSERT INTO GroupMembers (GroupCode,Member,MemberType) VALUES ('D','A','Group')INSERT INTO GroupMembers (GroupCode,Member,MemberType) VALUES ('D','4','Individual')INSERT INTO GroupMembers (GroupCode,Member,MemberType) VALUES ('E','C','Group')INSERT INTO GroupMembers (GroupCode,Member,MemberType) VALUES ('E','5','Individual')SELECT * FROM [dbo].[Groups]SELECT * FROM [dbo].[GroupMembers]

Need advice on this string manipulate scalar UDF

Posted: 09 Apr 2013 11:44 PM PDT

Dear all,[b]Can you please comment on this UDF, is there any better way to do it?For example CLF scalar UDF or inline table UDF?[/b]There is around 50 Million rows in TableABC and it will be around 1GB in size if it is exported as plain text .we want to use this function in this way:[code="sql"]SELECT 'D' AS RECORDTYPECODE, a.[Id],a.[Col1],a.[Col2],a.[Col3],%DBNAME%.ReplaceSplVarcharsBICD(a.[Col4]),%DBNAME%.ReplaceSplVarcharsBICD(a.[Col5]),%DBNAME%.ReplaceSplVarcharsBICD(a.[Col6]),a.[genID] FROM %DBNAME%.TableABC a[/code]The function is shown below:[code="sql"]USE [BPSUAT_BICD]GO/****** Object: UserDefinedFunction [dbo].[ReplaceSplVarcharsBICD] Script Date: 04/10/2013 16:08:15 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE function [dbo].[ReplaceSplVarcharsBICD](@value varchar(8000))RETURNS varchar(8000)asbegindeclare @result varchar(8000);-- This function is used to Replace some Special characters with space for varchar and char datatypes.-- Replacing for Enter, newlineselect @result = REPLACE(REPLACE(REPLACE(@value, CHAR(10) + CHAR(13), ' '),CHAR(10),' '), CHAR(13),' ');--Replacing other non printable characters from Hex 00 to Hex'1F' and Hex'7F'select @result = REPLACE(@result, CHAR(0),' ');select @result = REPLACE(@result, CHAR(1),' ');select @result = REPLACE(@result, CHAR(2),' ');select @result = REPLACE(@result, CHAR(3),' ');select @result = REPLACE(@result, CHAR(4),' ');select @result = REPLACE(@result, CHAR(5),' ');select @result = REPLACE(@result, CHAR(6),' ');select @result = REPLACE(@result, CHAR(7),' ');select @result = REPLACE(@result, CHAR(8),' ');select @result = REPLACE(@result, CHAR(9),' ');--select @result = REPLACE(@result, CHAR(10),' ');select @result = REPLACE(@result, CHAR(11),' ');select @result = REPLACE(@result, CHAR(12),' ');--select @result = REPLACE(@result, CHAR(13),' ');select @result = REPLACE(@result, CHAR(14),' ');select @result = REPLACE(@result, CHAR(15),' ');select @result = REPLACE(@result, CHAR(16),' ');select @result = REPLACE(@result, CHAR(17),' ');select @result = REPLACE(@result, CHAR(18),' ');select @result = REPLACE(@result, CHAR(19),' ');select @result = REPLACE(@result, CHAR(20),' ');select @result = REPLACE(@result, CHAR(21),' ');select @result = REPLACE(@result, CHAR(22),' ');select @result = REPLACE(@result, CHAR(23),' ');select @result = REPLACE(@result, CHAR(24),' ');select @result = REPLACE(@result, CHAR(25),' ');select @result = REPLACE(@result, CHAR(26),' ');select @result = REPLACE(@result, CHAR(27),' ');select @result = REPLACE(@result, CHAR(28),' ');select @result = REPLACE(@result, CHAR(29),' ');select @result = REPLACE(@result, CHAR(30),' ');select @result = REPLACE(@result, CHAR(31),' ');select @result = REPLACE(@result, CHAR(127),' ');--Replacing the pipe symbol select @result = REPLACE(@result, CHAR(124),' ');--Repalcing the NULsselect @result = Nullif(@result,'');--Removing the Right Spaces select @result = RTRIM(@result);--Removing the Left Spacesselect @result = LTRIM(@result);return @result;end[/code]or should we use CLF scalar UDF like this[code="VB"] using System; using System.Data.Sql; using System.Data.SqlTypes; using System.Collections.Generic; using Microsoft.SqlServer.Server; using System.Text; using System.Text.RegularExpressions; public partial class UserDefinedFunctions { [Microsoft.SqlServer.Server.SqlFunction] public static SqlString ReplaceSplVarcharsBICD(SqlString s){ if (s.IsNull) return String.Empty; //Removing the Right Spaces and Left Spaces string s1 = s.ToString().Trim(); if (s1.Length == 0) return String.Empty; StringBuilder tmpS = new StringBuilder(s1.Length); //striping out the "control characters" //Control characters are non-printing and formatting characters, such as ACK, BEL, CR, FF, LF, and VT. The Unicode standard assigns the following code points to control //characters: from \U0000 to \U001F, \U007F, and from \U0080 to \U009F. According to the Unicode standard, these values are to be interpreted as control characters unless //their use is otherwise defined by an application. Valid control characters are members of the UnicodeCategory.Control category. //Replacing for Enter, newline 0D0A or \x000D (13) or \x000A (10) //Replacing other non printable characters from Hex 00 to Hex'1F' and Hex'7F' subset of control characters //Replacing the pipe symbol \x007C (124) //Repalcing the NULs 00 for (int i = 0; i <= s1.Length; i++) { if (!Char.IsControl(s1[i]) & !s1[i] =='\x000D' & !s1[i] =='\x000A' & !s1[i] =='\x007C') { tmpS.Append(s1[i]); } else { tmpS.Append(' '); } } string result = tmpS.ToString().Trim(); return result; } }[/code]

comparing list to master list

Posted: 15 Apr 2013 05:25 PM PDT

How would you write a query that would return only the items in the where clause, which were not found in the table? ie. 'fff','ggg','hhh','iii' are not found in the table. I could build a second table with all the values in the where clause and do an except, but that is too much work...[code="plain"]create table List(id int,name varchar(20))insert into Listvalues(1,'aaa'),(2,'bbb'),(3,'ccc'),(4,'ddd'),(5,'eee'),(6,'jjj'),(7,'kkk'),(8,'lll');select * from Listwhere name not in ('ooo','bbb','ccc','ddd','eee','fff', 'ggg', 'hhh', 'iii', 'jjj','kkk','lll');[/code]

Can someone help with a TSQL date sorting issue?

Posted: 15 Apr 2013 01:59 PM PDT

I would like to retrieve data for all the fields listed in the query below. The problem is that I would like to partition Collection into 3 date fields then sort the columns by the most Resent date (DESC Order) See query and sample output below:SELECTName,MeterId,Collection Date,Collection Amount,MeterNumber,BlockfaceFROM dbo.CollectionSummaries C WITH(NOLOCK) JOIN Meters M WITH(NOLOCK) ON M.MeterId = C.MeterId LEFT JOIN RouteAssignments RA WITH(NOLOCK) ON RA.MeterId = M.MeterId LEFT JOIN [Routes] R WITH(NOLOCK) ON R.RouteId = RA.RouteId JOIN RouteTypes RT WITH(NOLOCK) ON RT.DisplayName = 'Collection' JOIN dbo.Blockfaces B WITH(NOLOCK) ON B.BlockFaceId = M.BlockFaceId JOIN dbo.Streets S WITH(NOLOCK) ON S.StreetId = B.StreetId WHERE AND R.RouteTypeId = 1 Group by Name, MeterId, CollectionDate, MeterNumber, Blockface Order by CollectionDate DESC[b]Sample Output[/b][b]Column #1 Column#2 (Column#3[/b] [u]CollectionDate1[/u] [u]CollectionDate2[/u] [u]CollectionDate3 [/u]2013/04/15 2013/03/01 2012/12/14 2013/04/14 2013/02/10 2012/11/022013/04/02 2013/01/30 2012/11/01Any suggestions would be greatly appreciated.Thanks

Using pivot in sql

Posted: 15 Apr 2013 02:18 AM PDT

Hello,I have a sql table as belowAutoId PID ItemId Item ItemValue Date7560 432 1 Wbc 4 05/05/12 00:007561 432 2 HCT 4 05/05/12 00:007562 432 3 W/L/M 4 05/05/12 00:007563 432 4 Bilirubin 485 06/05/12 00:007564 432 1 Wbc 45 06/05/12 00:007565 432 2 HCT 4 06/05/12 00:00 I tried to use the pivot to display the result as below. But it didn't worked for me. Does any one have any idea on how to get this done? AutoId PID ItemId Item 05/05/12 06/05/127560 432 1 Wbc 47561 432 2 HCT 47562 432 3 W/L/M 47563 432 4 Bilirubin 4857564 432 5 Wbc 457565 432 6 HCT 4Thanks,VIjay

Getting only Street name suite information from the address.

Posted: 15 Apr 2013 08:33 AM PDT

Hi All,Thanks for looking into my post, well I been scratching my head for a long time now the requirement which sound pretty simple turned out to be a tough one, below is the requirement....I need to seprate (Street Number, Street Name, Suite\Apt information or any zip found)Address looks like this1) 123 Main St2) 123 NW.17 St3) One Washington Way, Suite 4054) 1 Governement Dr #400, Washington, 01211So far I was able to seprate out 123 Main St, but whenever I go further using Char\Pat index in my string the address from above line 2 gets scramblled such as it becomes (123 NW St)My main gole is to break htis string and put it in a table and then concatinate.....Any help would be much appreciated.

SSMS Query Logging

Posted: 23 Sep 2012 07:31 PM PDT

We have a user who has come from an environment (SAS) where all of the queries she ran were logged, along with number of rows affected and any error messages.At the end of a session, she could save this log as a text file.A typical session would include a multitude of DML queries to move data around and populate calculated fields.She liked the fact that she could always go back and review the statements that were executed and how many rows were being affected and has asked whether we can provide something similar in SSMS.A brief investigation suggested not. The SSMS Tools add-on gets quite close with its SQL History functionality, but this does not capture errors or number of rows affected.I can write a stored proc which executes SQL for her and captures the required information, but this seems cumbersome because she'd have to wrap each of her queries with exec ''.Does anyone have any other ideas? Thanks in advance.

How the ssrs expressions works for DateDiff?

Posted: 15 Apr 2013 03:48 AM PDT

I'm working on SSRS reports there is on column i.e Holding period where we actually calculate forhow many days the company is hold in our database (we compare with buy date)and ssrs expression is=DateDiff(DateInterval.Day, Fields!BuyDate.Value, First(Fields!Date.Value, "DailyPosition"))Which is coming wrong could any one help to execute correct calulation.Buy date is a normal date column from table , and "DailyPosition" is my dataset name from ssrs report.for example Company ABC buy date is 2012-03-13 00:00:00.000 and last parameter date is 2012-12-31 00:00:00.000below query giving me result as 293 select DATEDIFF (day,'2012-03-13 00:00:00.000','2012-12-31 00:00:00.000')which is wrong as my holding period is 126 days onlyplease help me to correct the expression.

[SQL server issues] Commented Issue: AdventureWorksDW2008R2 DimDate table has missing dates [13383]


Hello,
Is this been taken care? If so, please share the latest data for DimDate. I'm working on some POC which requires dates in between 2008 and 2010 as well. If it is not already done, can someone let me know is there is any way I can generate the data for those missing dates in that table?



.

sqlserversamples.codeplex.com

Search This Blog