Posts

Showing posts with the label SQL Server

TSQL - String Concatenation

On current project, I ran into a scenario where I needed to concatenate a series of rows into a single string value.  Nothing major, just concatenate them with a delimiter and return the result.  As all of us Microsoft SQL developer's know and deal with is the lack of a SQL supported function that is able to assist us in this "minor" feature. As this is my knowledge dump for techniques and other methods used for the various platforms, here we go: Construct: The first step is to identify what information you want, the basic's of query design.   SELECT Email FROM Contacts Group By Email Group by is conditional, depending on your situation and how you organize your referential integrity. Stage Next, lets build our environment, not the SProc just the supporting actors in the process. declare @email varchar(max) = '' SELECT @email += Email + ', ' FROM Contacts Group By Email This simply concatenates each of ...

SQL Porosity - CSV Element Calculation

Image
Background: Recently "walked" into a scenario where a client was storing an variable sized CSV string in a field.  This field held data that would eventually be evaluated as a "pseudo" entity for reporting purposes. Problem Due to the need for performance and reliability, the normal practice of splitting the string into a result set and then performing a SQL Count on the result set, would be overly complex and may cause performance issues as the length is variable  (i.e. varchar(max) ) Solution After reviewing several search queries, which most ended up at my old faithful Stack Overflow .  I came across an approach that is nothing more than Porosity .  For my purpose, it fit the bill very cleanly without overly transitioning a single value into a data-set and then calculating the data-set. Net Result Data-Set : Source: SQL Data - Source Value SQL Data - Comma's Voided Math n -  Len([Field]) m  - Len(Replace([Field], ',', ...

Executing a Stored Procedure....The Proper Way

As we develop in Microsoft's Entity Framework family, we will at times run into a situation, or by design, the need to execute a Stored Procedure from the database (most likely Microsoft SQL Server ).  As we have discovered, they (Microsoft) evidently do not want us to do this inherently.  They hid the direct SProc execution well down into the Database object (off the DbContext object ) and even then it has a few names: SqlQuery and ExecuteSqlCommand .  Of course, both of these have their equivalent ASync execution versions. To make matters even more fun and interesting, is the problem of Ordinal execution.  Any proper DBA will tell you, if asked, that Ordinal execution is a bad implementation pattern.  And you developers, will simply respond: Well then don't change the order in which the Parameters exist.  Then the DBA responds, and the banter battle begins between a Developer and a DBA. My simple solution to avoid this whole needless verbal battle...

SQL - IsNullOrWhiteSpace Function

Just another SQL Code-snippet to check for NULL or whitespace value: -- ============================================= -- Author: John Wood -- Create date: 20151129 -- Description: Returns a boolean value -- ============================================= ALTER FUNCTION [Int].IsNullOrWhiteSpace ( -- Add the parameters for the function here @val sql_variant ) RETURNS bit AS BEGIN declare @ret bit if(SQL_VARIANT_PROPERTY(@val, 'BaseType') in ('varchar', 'nvarchar', 'char', 'nchar')) begin declare @char varchar = cast(@val as varchar) select @ret = iif(ltrim(rtrim(@char)) = '', 1, 0) end else begin -- Return the result of the function select @ret = iif( @val IS NULL, 1, 0 ) end return @ret END GO

Time Scalar Function

Everyone knows that you can use the Convert DML  to convert a DateTime data-type to a string evaluation for either split storage or display to an consuming interface. As most of us use the Date portion of a DateTime value for 90% of everything we are rendering the data to.  But what about that 10% where we either need to split render the Date & Time seperately.  After much review, we only have two quick and easy values to use and neither are really interchangeable. Option #1, with 2 forms: select convert(varchar(10), getdate(), 108) -- Produces: 13:53:15 select convert(varchar(15), getdate(), 114) -- Produces: 13:53:15:707 Now when using these forms of conversion, about 75% you have met the need for your requirement.  But lets say you need to use the Time string created for say a Filename ( sometext_[[TIME]].txt ), what do you do? Well the next code segment is what will be produced in order meet the FileName convention of special char...

Search Instance for a Stored Procedure usage

References: Peter Chamley MSSql Tips - Greg Robidoux: Listing SQL Server Object Dependencies Recently, I had the need to skim acrossed all the databases on a single instance.  In doing so I figured that the infamous 'sp_msforeachdb' undocumented stored procedure would be useful but was unsure on the methodology or pattern to implement.

SSMS 2012 - Template Modification

Ran into a situation where i needed to modify the standard templates that SSMS uses to Create Stored Procedures, Functions, and some other scripts. Problem: I did not know where to find these templates. First Solution: Goto Code Snippet Manager and modify snippets. Problem with this is that it requires you to create the XML snippet file and even then requires you to put it in, either the Public or Your Profile's, My Snippets folder. This does not solve the immediate problem as i would rather use the Context menu's New Stored Procedure (Function, etc). After-Thought: This solution though is great for things such as doing standard Select Statements for your organization.

SQL Agent Jobs - Non Maint Plan

While doing some development found a need to find non-Maintenance Plan Jobs for doing some reporting.  After couple minutes searching Google and some other sites, there is a huge lack of information or queries that effectively show how to obtain or tie system tables together to derive the literal SQL Agent Jobs. That being said, here is a little script i created that will query the system databases and produce a list of SQL Agent jobs. Code Snippet: 1: select * 2: from msdb.dbo.sysjobs as job 3: where job.job_id not in (select job_id from msdb.dbo.sysmaintplan_subplans)

Acquire SQL Service Account

Reference:  Jason Yousef Blog 1: DECLARE @SrvAccount varchar(100) 2: set @SrvAccount ='' 3: 4: EXECUTE master.dbo.xp_instance_regread 5: N'HKEY_LOCAL_MACHINE', 6: N'SYSTEM\CurrentControlSet\Services\SQLSERVERAGENT', 7: N'ObjectName', 8: @SrvAccount OUTPUT, 9: N'no_output' 10: 11: SELECT 12: @@SERVERNAME as [MachineName] 13: , @SrvAccount as SQLAgent_ServiceAccount

Linked Server....

Well today, I started the fun filled adventure of managing data from/to a LinkedServer. During this learning curve, I found plenty of information about how to query from and instert into a Linked server but most of them utilized the OpenQuery  TSQL Statement to operate. One failure of the concepts is to use the inline statement to access the Linked Server. In my situation, i was linking to a MySQL database offsite.  Below you will find the MSSQL statement patterns to used when utilizing query statements against the Linked Server. Select: 1: Select {cols} 2: From {LinkedServer}...{table} 3: [Conditions] Insert: 1: Insert Into {LinkedServer}...{table} [cols,...] 2: Values ([cols,...]) There are more commands you can use but the point is that the developer/dba is utilizing only the 'server' and 'table' portions of the source information.  This being, as described by Microsoft, as ' {server}.{database}.{schema}.{table} ' is simply ' ...

Maintenance Plan history

I have been researching for the last couple of weeks a way to acquire a maintenance plan job history, success or failure. After alot of searching and finding that no one has or is not sharing the ability to do this, I decided to start hacking away at the MS SQL 2005/2008 core databases to find the relationship. After much digging, there are a total of 4 tables you need to have access to, whether through a proxy account of dbo schema account. Tables in question: - msdb..sysmaintplan_log - msdb..sysmaintplan_logdetail - msdb..sysmaintplan_subplans - msdb..sysjobs (optional: gives the SQL Agent Job name) SQL Script as i built it, but you will probably modify it to your needs: 1: SELECT 2: mpld.server_name, 3: j.name, 4: mpl.start_time, 5: mpl.end_time, 6: mpl.succeeded, 7: mpld.error_number, 8: mpld.error_message, 9: mpld.line1 + char(10) + char(13) + 10: mpld.line2 + char(10) + char(13) + 11: mpld.line3 + ch...