Tag: T-SQL

  • Create a Linked Server: #SQLNewBlogger

    I had a customer recently that was asking about Linked Servers and some development advice. I was going to show them a few things and realized I hadn’t created a linked server in my demo environment, so I did it and decided to create a quick post on this.

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

    The Scenario

    I have a few demo instances of SQL Server in my local environment: Aristotle and Aristotle\SQL2022. In this case I was connected to the named instance, and decided to create a connection to Aristotle. As you can see, I don’t have any linked servers in the named instance.

    2025-04_0125

    To create a linked server, I can use this simple code:

    EXEC master.dbo.sp_addlinkedserver   
         @server = N'Aristotle',   
         @srvproduct=N'SQL Server';  
    GO

    This creates the linked server (as you can see below), with a number of defaults. In this case, the security is made with whatever login queries the linked server.

    2025-04_0126

    You can see the security properties here:

    2025-04_0127

    This might be OK in your enviroment, or it might not be. Perhaps you need to ensure everyone querying the remote server uses the same login. In which case, the sp_addlinkedserver procedure doesn’t do this. You would need to use sp_addlinkedsrvlogin to do that. That’s for another post.

    NOTE: Be sure you understand what a linked server does, how to use it, and the downsides. There are many and this can slow down your application or overload servers

    I can test this connection by right clicking the Linked Server in SSMS:

    2025-04_0128

    This works, as expected.

    2025-04_0129

    I can also run a query through the linked server, using 4-part naming with the linked server, then the database, schema, and table. This also works:

    2025-04_0160

    That’s it to get started. I recommend you be careful when using linked servers as this creates a bit of a tight coupling and makes development harder. I might recommend you get away from querying database server to database server when possible and let an application do this work if it’s possible.

    SQL New Blogger

    Linked Servers aren’t that common, but they aren’t rare. This is a skill that SQL Server people should have and understand a bit about. This post is very basic, but it provides a jumping off point where I could write a number of other posts related to linked servers and perhaps guide an interviewer along a path of asking me about them. I certainly showcase some knowledge here if someone asks me if I’ve ever created one.

    This post took me about 10 minutes to test and write, and you could probably do this in your environment. You don’t even need to servers, as you could create a loopback linked server.

  • Can I Change a Primary Key Value? #SQLNewBlogger

    I heard someone say recently that you can’t change a primary key value in a row. That’s not the case, so I decided to show a quick proof of that.

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

    The Scenario

    Let’s set up a simple table with some data.

    CREATE TABLE PKChangeTest (
    ImportantNumber VARCHAR(20) NOT NULL CONSTRAINT PKChangeTestPK PRIMARY KEY
    , CustomerName VARCHAR(50)
    , StatusValue INT)
    GO
    INSERT dbo.PKChangeTest
       (ImportantNumber, CustomerName, StatusValue)
    VALUES
       ('1234567', 'Steve', 1)
    ,  ('2345678', 'Andy', 1)
    ,  ('3456789', 'Brian', 1)
    ,  ('1235667', 'Leon', 1)
    ,  ('1265567', 'Dave', 1)
    ,  ('9914567', 'Bill', 1)
    GO

    If I look at this table, I have some unique numbers making up the PKs. If I select from the table, I can see the data.

    2025-04_0117

    Now, let’s change some data. I’ll change the PK values with a few statements. Then I’ll select from the table, and we will see things changed.

    2025-04_0118

    The ImportantNumber for both Bill and Steve have changed. These are PK modifications.

    We can change a PK value. These are not set in stone once inserted.

    SQL New Blogger

    This is a short look at something that’s a myth among some people. When I heard someone say this, I knew I needed to prove this. The scenario took just about 5 minutes to set up (even without AI), and then it was another 10 minutes to structure and write this post.  I actually have 2 more ideas from this on things I can show to prove how PKs work and are malleable.

    You can do the same thing. When you wonder about something, or hear something that isn’t true from others, prove it. And blog about it.

  • Limiting Results with TEXTSIZE in SQL Server: #SQLNewBlogger

    There is a SET command in SQL Server that changes how much data is returned from some fields. This short post shows what I learned about the SET TEXTSIZE command.

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

    The Scenario

    Let’s start with a little code. I actually created a table that looks like this:

    CREATE TABLE [dbo].[Beer]
    (
    [BeerID] [int] NOT NULL IDENTITY(1, 1),
    [BeerName] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    [brewer] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    [beerdescription] [varchar] (max) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
    ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
    GO

    I added data so that I have something in here:

    INSERT INTO dbo.Beer
       (BeerName, brewer, beerdescription)
    VALUES
      (1,    'Becks', 'Interbrew', 'Beck''s is a German-style pilsner beer known for its golden color, full-bodied taste, and a crisp, clean finish with floral and fruity hop aromas, brewed according to the German purity law')
    ,(2,    'Fat Tire', 'New Belgium    Toasty malt, gentle sweetness, flash of fresh hop bitterness. The malt and hops are perfectly balanced.')
    ,(3,    'Mac n Jacks', 'Mac & Jack''s Brewery', 'This beer erupts with a floral, hoppy taste, followed by a well rounded malty middle, finishing with a nicely organic hop flavor. Locally sourced two row grain and a blend of specialty malts give our amber its rich taste.')
    ,(4,    'Alaskan Amber', 'Alaskan Brewing', 'Alaskan Brewing Amber Ale is an "alt" style beer, meaning it''s fermented slowly and at colder temperatures, resulting in a well-balanced, richly malty, and long-lasting flavor profile with a clean, pleasing aftertaste.')
    ,(8,    'Kirin', 'Kirin Brewing', 'Kirin Ichiban is a Lager-type beer, which means it is fermented at low temperatures and offers a light and refreshing texture with a smooth and balanced flavor.')

    Now, let’s see what this setting does.

    SET TEXTSIZE

    This command changes the behavior of SELECT queries and controls how much data is returned in bytes. The setting is the command with an integer after it. The max value is 2GB.

    I’ll run a normal query, then I’ll set a smaller size and repeat the query. Notice how the results differ below. I get less data in the second query.

    2025-04_0218

    What this setting does is limit the number of bytes from some fields. I only have 20 characters from each description.

    Let’s do one more query. I’ll lower the value to 5.

    2025-04_0219

    Note that while the description is very low, the name and brewer are not cut off.

    The explanation is that this works on the max types: varchar(max), nvarchar(max), varvinary(max), text, ntext, and image. Non-max fields aren’t affected.

    Also note that the default setting from the SQL Native Client and ODBC driver is –1, for unlimited data. That explains why I haven’t noticed this as I’m often using an app that uses one of those. IF you set this to 0, then it defaults to 4KB.

    A nice way to prevent apps from grabbing tons of data unless they need it, though you’d certainly need to help users understand why they weren’t getting all the data expected. I think long fields (or image/audio/etc. data) would need a “get more” or “get all” item in software to reset this and return the full value in the table.

    SQL New Blogger

    This was a function I ran across, whose purpose I had no idea about. I read it, experimented, and in about 30 minutes had put together this demo and post. Easy to do and quick.

    I learned something, and I’m sharing this with potential employers. You could as well, with a little effort.

  • CHOOSE’ing a Beer: #SQLNewBlogger

    We recently published an article on CHOOSE at SQL Server Central. I thought it was a good intro, but as someone noted in the comments, how do you use CHOOSE? Do you have to hard code choices?

    This post shows you don’t.

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

    A Scenario

    I have a table that contains some data. In this case, about beer. I like beer, and this was a fun little demo. I’m not recreating the DDL because, well, you might like different beers.

    2025-03_0145

    In any case, this is simple to set up.

    If I wanted to choose some data from this table based on an index, I could do something like this. This code populates the first index in choose with beers and the second with brewers. CHOOSE is 1-based indexing.

    DECLARE @i INT = 1;
    SELECT
       CHOOSE (@i, beername, brewer)
    FROM dbo.Beer AS b2;

    This returns me the beers.

    2025-03_0146

    If I changed the value to 2, I get brewers. I show both below.

    2025-03_0147

    How would I use this? Maybe a user is asking to edit either a home or shipping address. I can index these by returning the column data as index 1 or 2, and linking the user suggestion to the index. They choose home, we pass in 1. If we qualify the query with a WHERE clause to one customer, they get just their data to edit.

    I could even do something silly, like getting values from different places. For example, here I’ll use string_split on a value.

    DECLARE @i INT = 2;
    DECLARE @s VARCHAR(20) = 'Vodka,Tequila,Bourbon'
    
    ; WITH a (value)
    AS
    (SELECT a.value FROM STRING_SPLIT(@s, ',', 1) AS a
      WHERE a.ordinal = 1
    ),
      b (value)
    AS
    (SELECT a.value FROM STRING_SPLIT(@s, ',', 1) AS a
      WHERE a.ordinal = 2
    ),
      c (value)
    AS
    (SELECT a.value FROM STRING_SPLIT(@s, ',', 1) AS a
      WHERE a.ordinal = 3
    ) 
    SELECT
       CHOOSE (@i, a.value, b.value, c.value)
      FROM a, b, c

    This is silly, but it does return an acceptable answer.

    2025-03_0148

    I don’t know that there are many places that I’d use CHOOSE, but as I play with it, I can see that it could be a handy tool at times with a little creativity.

    SQL New Blogger

    This post took me about 15 minutes to write after I saw a comment. I set up a scenario and posted a reply, then took that code to structure this post. The STRING_SPLIT piece was the longest, as I had to futz with code, but I show some use of a new feature and how I might incorporate this into an application.

    You could write your own creative blog on this, probably in 30 minutes or less. I bet you’d get asked about this in an interview as it’s kind of funny.