Tag: T-SQL

  • Adding Extended Properties

    Another post for me that is simple and hopefully serves as an example for people trying to get blogging as#SQLNewBloggers.

    One of the things I needed to do recently was add some extended properties to objects. I got the idea of using them from John McClusky at SQL Bits. He had a great presentation on tSQLt that’s worth watching.

    In any case, I wanted to add, and update, extended properties.  I had used SSMS to do this, but it’s cumbersome. I decided to experiment and see how the T-SQL code works. My browsing of Books Online showed me there are a few procedures used, one each for adding, updating, and deleting properties. I decided to start with sp_addextendedproperty.

    This procedure takes some interesting, rather unintuitive arguments. Name and value are easy to understand. These are the name of the property and it’s assigned value. One thing to note is that value is a sql_variant, which should work fine for most situations, but CASTing may be required.

    However the next arguments are level 0, 1, and 2, with a type and name for each. Those didn’t make much sense at first. In fact, as I wrote a few scripts, I had to keep looking up the meanings. Essentially we have three classifications of objects. The outer containers, the objects, and the dependent objects. I’ll explain them below.

    The level0 type is essentially the class of object. Is this an Assembly, a Contract, a Schema, etc. For my purposes, this has always been a schema, but certainly you could add properties to the other classes if you needed them.

    The level1 is the object type that we usually work with: table, view, function, procedure. For me this is pretty much been table, view or procedure, but certainly function is something I’d use as well.

    The level2 is the dependent object: the trigger, the column, the parameter, the constraint. These I haven’t really used, but I certainly think that adding in properties for indexes, triggers, etc are valuable.

    Adding a property is easy. For example, one of the items I add is a PK exception for heap tables. To do that (for the SalesHeader_Staging table), I’d run this.

    EXEC sys.sp_addextendedproperty 
      @name = 'PKException',
      @value = 1, -- sql_variant
      @level0type = 'schema', -- varchar(128)
      @level0name = 'dbo', -- sysname
      @level1type = 'table', -- varchar(128)
      @level1name = 'SalesHeader_Staging' -- sysname
      ;
    GO
    
    

    I can see this easily in SSMS.

    2015-11-02 17_16_53-Table Properties - SalesHeader_Staging

    Properties are great ways to add additional information to an object in SQL Server, though I certainly wish they were more visible in objects.

    SQLNewBlogger

    I knew there was a procedure to do this, and a quick search on extended properties got me to the BOL reference. I was experimenting with adding the properties while working on this, and I had to research the meanings of the parameters a bit, so this took about 20 minutes to get ready for publication.

    Reference

    A few items from BOL

    sp_addextendedproperty – https://msdn.microsoft.com/en-us/library/ms180047.aspx

  • Using Automated Tests to Raise Code Quality

    Abstract

    Agile development practices can speed the development of applications and increase the rate at which you can deploy features for your customers. But unless you include a high level of test coverage in your code, these practices can also increase the number of bugs that are released. Databases can be particularly challenging for developers. This session examines database refactorings that introduce bugs, which are detected by automated tests. This approach allows developers to rapidly fix their code before a customer is affected.

    Level: 200

    Demos

    These are the demos shown in this talk.

    • Adding test data inline
    • Added test data in a procedure
    • Adding test data from a separate set of tables.
    • Exclusions to SQL Cop or other tests with Extended Properties.
    • Using FakeFunction
    • Using SpyProcedure
    • The boundary issues with multiple requirements for a function.
    • 0-1-Some testing
    • Catching dependencies.

    Downloads

    Here are the downloads for the talk.

  • What’s a Code Smell?

    We all have a variety of code patterns and practices that we follow. Most of them were probably picked up along the path of our career. A suggestion from a colleague. A piece of sample code that solved a problem. A performance tuning trick that stopped our phone from ringing. These methods of learning are the way that most of us actually grow our skills over time.

    However just because we learned something, or because a technique solved a problem doesn’t mean it was a good piece of code. In fact, often the code we may think works well might not be the most efficient way to structure the code. Many developers have learned this over the years, as they read about new techniques that are more efficent, elegant, or just simpler.

    Kent Beck and Massimo Arnoldi coined the term code smell years ago, as a way of noting the development patterns and practices that  lead to poorly written, or difficult to maintain code. There have been other attempts to document practices which are not recommended, though the success is probably limited as many developers continue to build on poorly written code rather than refactoring and cleaning their codebase over time.

    Simple Talk  and Phil Factor published a SQL Code Smells ebook awhile back, trying to document the signs of poorly written T-SQL. The book is good, with guidance about particular patterns that can cause you problems over time. The items aren’t meant to be rules, but rather guidelines that you adhere to unless you have a good, specific reason that you can justify to others.

    I ran into a code smell recently where a developer noted that their application depended on a specific database name in order to work.  That’s not in the ebook, but I think it’s easily one I’d avoid. My connection should determine the database, not the application itself. I know there may be exceptions here, but in general, application code shouldn’t be dependent on a particular name.

    I’d urge you to pick up the ebook (it’s free) and keep it handy. See if any of the items listed are habits you might have picked up over time and not realized that they are, in fact, poor practices. I would also recommend you peruse Aaron Bertrand’s Bad Habits to Kick series, as a way of improving your own code.

    Steve Jones

    The Voice of the DBA Podcast

    Listen to the MP3 Audio ( 2.9MB) podcast or subscribe to the feed at iTunes and LibSyn.

  • Use SCOPE_IDENTITY()–SQLNewBlogger

    Another post for me that is simple and hopefully serves as an example for people trying to get blogging as #SQLNewBloggers.

    I ran across a question on Facebook, of all places, the other day. Someone had asked a friend how to return a value from a procedure and assign it to a variable. My friend answered, but in the discussion, I noticed the poster was looking to return @@IDENTITY to the calling procedure as the value of the row that was just inserted.

    Don’t do that. At least not without understanding the potential issues.

    It’s been years since I’ve seen @@IDENTITY in use, and for a number of years before that, this was an easy “weed out” question in interviews.

    If you look at the documentation for @@IDENTITY, the documentation notes that SCOPE_IDENTITY() and @@IDENTITY both return the last identity value inserted in the table, but @@IDENTITY is not limited in scope to the current session.  This means that when concurrent inserts occur, you could receive the identity value of another session. Depending on how you use this value, that may or may not be an issue.

    How does this work? Let’s create a simple table with an identity. I also create a logging table and a trigger that will add a message to my logging table when I add a row to the first table.

    CREATE TABLE newtable
        (
          id INT IDENTITY(1 ,1)
        , mychar VARCHAR(20)
        );
    GO
    CREATE TABLE Logger
     (logid INT IDENTITY(56,1)
     , logdate DATETIME
     , msg VARCHAR(2000)
     );
    GO
    CREATE TRIGGER newtable_logger ON dbo.newtable FOR INSERT
    as
      INSERT INTO logger VALUES (GETDATE(), 'New value inserted into newtable.')
    RETURN
    ;
    go
    

    If I run this, what do I expect to be returned?

    INSERT INTO dbo.newtable
            ( mychar )
    VALUES  ( 'First row'  -- mychar - varchar(20)
              )
    
    SELECT @@IDENTITY
    
    
    
    

    However I get this. A 56 in my result set for @@identity.

    2015-09-22 17_32_20-Cortana

    Why?

    The reason is that the last identity value was 56, from the logging table. The order of operations is

    • insert value into newtable
    • @@identity set to 1
    • trigger fires
    • insert into logger
    • @@identity set to 56

    That’s often not what we want when capturing an identity value. What’s worse, this behavior can exist, but not manifest itself until someone changes a trigger later.

    If I change this SCOPE_IDENTITY(), I get a different result.

    2015-09-22 17_38_26-Start

    This is because the SCOPE_IDENTITY() function takes the scope into account and doesn’t get reset by the trigger code.

    SQLNewBlogger

    This took some time to write. Mostly because I had to setup the demo, test things, and then get the explanation straight in my head. It took me 15-20 minutes, including lookup time in BOL, but if you are new to writing, this might take a bit longer. You’d also want someone to review your explanation since this can be tricky to explain.

    Reference

    • @@IDENTITY
    • SCOPE_IDENTITY()