Any way to create function/method in SQL for combining columns in the SELECT?










0















Wrote a great simple function in SQL that apparently is not usable (or advisable) in my SELECT statement.



Have some intelligence behind combining Combinations of Company Name and Contact Name in our select and I find it's repeating across several views. Being a programmer, of course the right thing is to encapsulate that functionality for reuse across all views I'm created. But alas, from my searching it does not appear possible or recommended, at least not with UDFs.



The question: Is there any way to select the return value of a method/function/chunk of reusable code where I pass it the value of columns for each row... Or do I truly have to copy/paste the logic into each select statement?



SELECT formatName(company, contact, ' - ') as Name FROM company join contacts...


I know I can do this on the client (eventually), but client changes are not in scope for this phase of the project.



I guess I typed more in this question than just cutting and pasting a CASE statement into each view, but reuse is ingrained if me of course. :)










share|improve this question



















  • 2





    What are you trying to do with these columns? Is it just string concatenation or do you have some other formatting needed?

    – SteveD
    Nov 14 '18 at 15:35











  • @SteveD - Either one can be null or blank, so it's like if both are valid, concatenate them... and if only one or the other just that one, etc... Simple logic, but repeated.

    – klkitchens
    Nov 14 '18 at 15:48















0















Wrote a great simple function in SQL that apparently is not usable (or advisable) in my SELECT statement.



Have some intelligence behind combining Combinations of Company Name and Contact Name in our select and I find it's repeating across several views. Being a programmer, of course the right thing is to encapsulate that functionality for reuse across all views I'm created. But alas, from my searching it does not appear possible or recommended, at least not with UDFs.



The question: Is there any way to select the return value of a method/function/chunk of reusable code where I pass it the value of columns for each row... Or do I truly have to copy/paste the logic into each select statement?



SELECT formatName(company, contact, ' - ') as Name FROM company join contacts...


I know I can do this on the client (eventually), but client changes are not in scope for this phase of the project.



I guess I typed more in this question than just cutting and pasting a CASE statement into each view, but reuse is ingrained if me of course. :)










share|improve this question



















  • 2





    What are you trying to do with these columns? Is it just string concatenation or do you have some other formatting needed?

    – SteveD
    Nov 14 '18 at 15:35











  • @SteveD - Either one can be null or blank, so it's like if both are valid, concatenate them... and if only one or the other just that one, etc... Simple logic, but repeated.

    – klkitchens
    Nov 14 '18 at 15:48













0












0








0








Wrote a great simple function in SQL that apparently is not usable (or advisable) in my SELECT statement.



Have some intelligence behind combining Combinations of Company Name and Contact Name in our select and I find it's repeating across several views. Being a programmer, of course the right thing is to encapsulate that functionality for reuse across all views I'm created. But alas, from my searching it does not appear possible or recommended, at least not with UDFs.



The question: Is there any way to select the return value of a method/function/chunk of reusable code where I pass it the value of columns for each row... Or do I truly have to copy/paste the logic into each select statement?



SELECT formatName(company, contact, ' - ') as Name FROM company join contacts...


I know I can do this on the client (eventually), but client changes are not in scope for this phase of the project.



I guess I typed more in this question than just cutting and pasting a CASE statement into each view, but reuse is ingrained if me of course. :)










share|improve this question
















Wrote a great simple function in SQL that apparently is not usable (or advisable) in my SELECT statement.



Have some intelligence behind combining Combinations of Company Name and Contact Name in our select and I find it's repeating across several views. Being a programmer, of course the right thing is to encapsulate that functionality for reuse across all views I'm created. But alas, from my searching it does not appear possible or recommended, at least not with UDFs.



The question: Is there any way to select the return value of a method/function/chunk of reusable code where I pass it the value of columns for each row... Or do I truly have to copy/paste the logic into each select statement?



SELECT formatName(company, contact, ' - ') as Name FROM company join contacts...


I know I can do this on the client (eventually), but client changes are not in scope for this phase of the project.



I guess I typed more in this question than just cutting and pasting a CASE statement into each view, but reuse is ingrained if me of course. :)







sql-server sql-server-2008






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 14 '18 at 16:30









scsimon

22.1k51536




22.1k51536










asked Nov 14 '18 at 15:20









klkitchensklkitchens

55021136




55021136







  • 2





    What are you trying to do with these columns? Is it just string concatenation or do you have some other formatting needed?

    – SteveD
    Nov 14 '18 at 15:35











  • @SteveD - Either one can be null or blank, so it's like if both are valid, concatenate them... and if only one or the other just that one, etc... Simple logic, but repeated.

    – klkitchens
    Nov 14 '18 at 15:48












  • 2





    What are you trying to do with these columns? Is it just string concatenation or do you have some other formatting needed?

    – SteveD
    Nov 14 '18 at 15:35











  • @SteveD - Either one can be null or blank, so it's like if both are valid, concatenate them... and if only one or the other just that one, etc... Simple logic, but repeated.

    – klkitchens
    Nov 14 '18 at 15:48







2




2





What are you trying to do with these columns? Is it just string concatenation or do you have some other formatting needed?

– SteveD
Nov 14 '18 at 15:35





What are you trying to do with these columns? Is it just string concatenation or do you have some other formatting needed?

– SteveD
Nov 14 '18 at 15:35













@SteveD - Either one can be null or blank, so it's like if both are valid, concatenate them... and if only one or the other just that one, etc... Simple logic, but repeated.

– klkitchens
Nov 14 '18 at 15:48





@SteveD - Either one can be null or blank, so it's like if both are valid, concatenate them... and if only one or the other just that one, etc... Simple logic, but repeated.

– klkitchens
Nov 14 '18 at 15:48












2 Answers
2






active

oldest

votes


















1














A better performing and DRY method to accomplish this is with a computed column.




A computed column is a virtual column that is not physically stored in
the table, unless the column is marked PERSISTED. A computed column
expression can use data from other columns to calculate a value for
the column to which it belongs. You can specify an expression for a
computed column in SQL Server 2017 by using SQL Server Management
Studio or Transact-SQL.




You can make this column persisted as well




PERSISTED Specifies that the Database Engine will physically store the
computed values in the table, and update the values when any other
columns on which the computed column depends are updated. Marking a
computed column as PERSISTED allows an index to be created on a
computed column that is deterministic, but not precise. For more
information, see Indexes on Computed Columns. Any computed columns
used as partitioning columns of a partitioned table must be explicitly
marked PERSISTED. computed_column_expression must be deterministic
when PERSISTED is specified.




alter table company add FullName as (FirstName + '-' + LastName) persisted;


Then, you could just add this column in your SELECT can can even query against it, if it's persisted.






share|improve this answer























  • Thanks for the lead... Downside is this is for SQL 2008 and unless I can put more code in there than simple concatenation, it won't work for our needs... Also this is part of a view, with the data coming from Company and Contact to produce the combined value. :( Good tip though and something else to keep in my toolbox for other needs when possible.

    – klkitchens
    Nov 14 '18 at 16:39






  • 1





    well. you could create a view that has your FullName logic and query it instead of the base table, which would keep you from using a scalar function

    – scsimon
    Nov 14 '18 at 16:43











  • Which is the source of the original question. Several of the views I'm creating all need this same logic... which is what I'm hoping to avoid. Oh well, it's looking like it's not doable... apart from creating possible a single view that has the concatenated/calculated value, then joining to that in addition to the source tables for other information. At that point, it's more convoluted than just cutting and pasting the CASE statement in each view creation. Thanks again.

    – klkitchens
    Nov 14 '18 at 16:58






  • 1





    Yeah and querying nested views is a performance nightmare. I'd opt for the case

    – scsimon
    Nov 14 '18 at 17:27


















1














What you can do is create a view that behaves like a table. Meaning it would have the performance of a table, can have indexes added etc. This view can have any of the columns of the underlying base table plus you can add calculated columns, such as [name]. This is accomplished by adding WITH SCHEMABINDING when creating the view. This view can then be used in lieu of the base table in all of your queries.



Here is an example.
The underlying base table with data:



CREATE TABLE dbo.company (
companyid int IDENTITY(1,1) NOT NULL,
company varchar(50) NULL,
contact varchar(50) NULL,
CONSTRAINT PK_company PRIMARY KEY CLUSTERED (companyid ASC)
) ON FG1


The view containing WITH SCHEMABINDING:



CREATE view dbo.VW_company WITH SCHEMABINDING AS 
SELECT companyid,
CASE WHEN RTRIM(ISNULL(company,'')) <> '' AND RTRIM(ISNULL(contact,'')) <> '' THEN company +' - '+ contact
WHEN RTRIM(ISNULL(company,'')) <> '' THEN company
WHEN RTRIM(ISNULL(contact,'')) <> '' THEN contact
ELSE '' END as [Name]
FROM dbo.company


This view can now be used everywhere the table is used, without a performance hit. Furthermore, the calculated column [Name] can actually have an index added to it! That's something you cannot do with a function.






share|improve this answer






















    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53303454%2fany-way-to-create-function-method-in-sql-for-combining-columns-in-the-select%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    A better performing and DRY method to accomplish this is with a computed column.




    A computed column is a virtual column that is not physically stored in
    the table, unless the column is marked PERSISTED. A computed column
    expression can use data from other columns to calculate a value for
    the column to which it belongs. You can specify an expression for a
    computed column in SQL Server 2017 by using SQL Server Management
    Studio or Transact-SQL.




    You can make this column persisted as well




    PERSISTED Specifies that the Database Engine will physically store the
    computed values in the table, and update the values when any other
    columns on which the computed column depends are updated. Marking a
    computed column as PERSISTED allows an index to be created on a
    computed column that is deterministic, but not precise. For more
    information, see Indexes on Computed Columns. Any computed columns
    used as partitioning columns of a partitioned table must be explicitly
    marked PERSISTED. computed_column_expression must be deterministic
    when PERSISTED is specified.




    alter table company add FullName as (FirstName + '-' + LastName) persisted;


    Then, you could just add this column in your SELECT can can even query against it, if it's persisted.






    share|improve this answer























    • Thanks for the lead... Downside is this is for SQL 2008 and unless I can put more code in there than simple concatenation, it won't work for our needs... Also this is part of a view, with the data coming from Company and Contact to produce the combined value. :( Good tip though and something else to keep in my toolbox for other needs when possible.

      – klkitchens
      Nov 14 '18 at 16:39






    • 1





      well. you could create a view that has your FullName logic and query it instead of the base table, which would keep you from using a scalar function

      – scsimon
      Nov 14 '18 at 16:43











    • Which is the source of the original question. Several of the views I'm creating all need this same logic... which is what I'm hoping to avoid. Oh well, it's looking like it's not doable... apart from creating possible a single view that has the concatenated/calculated value, then joining to that in addition to the source tables for other information. At that point, it's more convoluted than just cutting and pasting the CASE statement in each view creation. Thanks again.

      – klkitchens
      Nov 14 '18 at 16:58






    • 1





      Yeah and querying nested views is a performance nightmare. I'd opt for the case

      – scsimon
      Nov 14 '18 at 17:27















    1














    A better performing and DRY method to accomplish this is with a computed column.




    A computed column is a virtual column that is not physically stored in
    the table, unless the column is marked PERSISTED. A computed column
    expression can use data from other columns to calculate a value for
    the column to which it belongs. You can specify an expression for a
    computed column in SQL Server 2017 by using SQL Server Management
    Studio or Transact-SQL.




    You can make this column persisted as well




    PERSISTED Specifies that the Database Engine will physically store the
    computed values in the table, and update the values when any other
    columns on which the computed column depends are updated. Marking a
    computed column as PERSISTED allows an index to be created on a
    computed column that is deterministic, but not precise. For more
    information, see Indexes on Computed Columns. Any computed columns
    used as partitioning columns of a partitioned table must be explicitly
    marked PERSISTED. computed_column_expression must be deterministic
    when PERSISTED is specified.




    alter table company add FullName as (FirstName + '-' + LastName) persisted;


    Then, you could just add this column in your SELECT can can even query against it, if it's persisted.






    share|improve this answer























    • Thanks for the lead... Downside is this is for SQL 2008 and unless I can put more code in there than simple concatenation, it won't work for our needs... Also this is part of a view, with the data coming from Company and Contact to produce the combined value. :( Good tip though and something else to keep in my toolbox for other needs when possible.

      – klkitchens
      Nov 14 '18 at 16:39






    • 1





      well. you could create a view that has your FullName logic and query it instead of the base table, which would keep you from using a scalar function

      – scsimon
      Nov 14 '18 at 16:43











    • Which is the source of the original question. Several of the views I'm creating all need this same logic... which is what I'm hoping to avoid. Oh well, it's looking like it's not doable... apart from creating possible a single view that has the concatenated/calculated value, then joining to that in addition to the source tables for other information. At that point, it's more convoluted than just cutting and pasting the CASE statement in each view creation. Thanks again.

      – klkitchens
      Nov 14 '18 at 16:58






    • 1





      Yeah and querying nested views is a performance nightmare. I'd opt for the case

      – scsimon
      Nov 14 '18 at 17:27













    1












    1








    1







    A better performing and DRY method to accomplish this is with a computed column.




    A computed column is a virtual column that is not physically stored in
    the table, unless the column is marked PERSISTED. A computed column
    expression can use data from other columns to calculate a value for
    the column to which it belongs. You can specify an expression for a
    computed column in SQL Server 2017 by using SQL Server Management
    Studio or Transact-SQL.




    You can make this column persisted as well




    PERSISTED Specifies that the Database Engine will physically store the
    computed values in the table, and update the values when any other
    columns on which the computed column depends are updated. Marking a
    computed column as PERSISTED allows an index to be created on a
    computed column that is deterministic, but not precise. For more
    information, see Indexes on Computed Columns. Any computed columns
    used as partitioning columns of a partitioned table must be explicitly
    marked PERSISTED. computed_column_expression must be deterministic
    when PERSISTED is specified.




    alter table company add FullName as (FirstName + '-' + LastName) persisted;


    Then, you could just add this column in your SELECT can can even query against it, if it's persisted.






    share|improve this answer













    A better performing and DRY method to accomplish this is with a computed column.




    A computed column is a virtual column that is not physically stored in
    the table, unless the column is marked PERSISTED. A computed column
    expression can use data from other columns to calculate a value for
    the column to which it belongs. You can specify an expression for a
    computed column in SQL Server 2017 by using SQL Server Management
    Studio or Transact-SQL.




    You can make this column persisted as well




    PERSISTED Specifies that the Database Engine will physically store the
    computed values in the table, and update the values when any other
    columns on which the computed column depends are updated. Marking a
    computed column as PERSISTED allows an index to be created on a
    computed column that is deterministic, but not precise. For more
    information, see Indexes on Computed Columns. Any computed columns
    used as partitioning columns of a partitioned table must be explicitly
    marked PERSISTED. computed_column_expression must be deterministic
    when PERSISTED is specified.




    alter table company add FullName as (FirstName + '-' + LastName) persisted;


    Then, you could just add this column in your SELECT can can even query against it, if it's persisted.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Nov 14 '18 at 16:30









    scsimonscsimon

    22.1k51536




    22.1k51536












    • Thanks for the lead... Downside is this is for SQL 2008 and unless I can put more code in there than simple concatenation, it won't work for our needs... Also this is part of a view, with the data coming from Company and Contact to produce the combined value. :( Good tip though and something else to keep in my toolbox for other needs when possible.

      – klkitchens
      Nov 14 '18 at 16:39






    • 1





      well. you could create a view that has your FullName logic and query it instead of the base table, which would keep you from using a scalar function

      – scsimon
      Nov 14 '18 at 16:43











    • Which is the source of the original question. Several of the views I'm creating all need this same logic... which is what I'm hoping to avoid. Oh well, it's looking like it's not doable... apart from creating possible a single view that has the concatenated/calculated value, then joining to that in addition to the source tables for other information. At that point, it's more convoluted than just cutting and pasting the CASE statement in each view creation. Thanks again.

      – klkitchens
      Nov 14 '18 at 16:58






    • 1





      Yeah and querying nested views is a performance nightmare. I'd opt for the case

      – scsimon
      Nov 14 '18 at 17:27

















    • Thanks for the lead... Downside is this is for SQL 2008 and unless I can put more code in there than simple concatenation, it won't work for our needs... Also this is part of a view, with the data coming from Company and Contact to produce the combined value. :( Good tip though and something else to keep in my toolbox for other needs when possible.

      – klkitchens
      Nov 14 '18 at 16:39






    • 1





      well. you could create a view that has your FullName logic and query it instead of the base table, which would keep you from using a scalar function

      – scsimon
      Nov 14 '18 at 16:43











    • Which is the source of the original question. Several of the views I'm creating all need this same logic... which is what I'm hoping to avoid. Oh well, it's looking like it's not doable... apart from creating possible a single view that has the concatenated/calculated value, then joining to that in addition to the source tables for other information. At that point, it's more convoluted than just cutting and pasting the CASE statement in each view creation. Thanks again.

      – klkitchens
      Nov 14 '18 at 16:58






    • 1





      Yeah and querying nested views is a performance nightmare. I'd opt for the case

      – scsimon
      Nov 14 '18 at 17:27
















    Thanks for the lead... Downside is this is for SQL 2008 and unless I can put more code in there than simple concatenation, it won't work for our needs... Also this is part of a view, with the data coming from Company and Contact to produce the combined value. :( Good tip though and something else to keep in my toolbox for other needs when possible.

    – klkitchens
    Nov 14 '18 at 16:39





    Thanks for the lead... Downside is this is for SQL 2008 and unless I can put more code in there than simple concatenation, it won't work for our needs... Also this is part of a view, with the data coming from Company and Contact to produce the combined value. :( Good tip though and something else to keep in my toolbox for other needs when possible.

    – klkitchens
    Nov 14 '18 at 16:39




    1




    1





    well. you could create a view that has your FullName logic and query it instead of the base table, which would keep you from using a scalar function

    – scsimon
    Nov 14 '18 at 16:43





    well. you could create a view that has your FullName logic and query it instead of the base table, which would keep you from using a scalar function

    – scsimon
    Nov 14 '18 at 16:43













    Which is the source of the original question. Several of the views I'm creating all need this same logic... which is what I'm hoping to avoid. Oh well, it's looking like it's not doable... apart from creating possible a single view that has the concatenated/calculated value, then joining to that in addition to the source tables for other information. At that point, it's more convoluted than just cutting and pasting the CASE statement in each view creation. Thanks again.

    – klkitchens
    Nov 14 '18 at 16:58





    Which is the source of the original question. Several of the views I'm creating all need this same logic... which is what I'm hoping to avoid. Oh well, it's looking like it's not doable... apart from creating possible a single view that has the concatenated/calculated value, then joining to that in addition to the source tables for other information. At that point, it's more convoluted than just cutting and pasting the CASE statement in each view creation. Thanks again.

    – klkitchens
    Nov 14 '18 at 16:58




    1




    1





    Yeah and querying nested views is a performance nightmare. I'd opt for the case

    – scsimon
    Nov 14 '18 at 17:27





    Yeah and querying nested views is a performance nightmare. I'd opt for the case

    – scsimon
    Nov 14 '18 at 17:27













    1














    What you can do is create a view that behaves like a table. Meaning it would have the performance of a table, can have indexes added etc. This view can have any of the columns of the underlying base table plus you can add calculated columns, such as [name]. This is accomplished by adding WITH SCHEMABINDING when creating the view. This view can then be used in lieu of the base table in all of your queries.



    Here is an example.
    The underlying base table with data:



    CREATE TABLE dbo.company (
    companyid int IDENTITY(1,1) NOT NULL,
    company varchar(50) NULL,
    contact varchar(50) NULL,
    CONSTRAINT PK_company PRIMARY KEY CLUSTERED (companyid ASC)
    ) ON FG1


    The view containing WITH SCHEMABINDING:



    CREATE view dbo.VW_company WITH SCHEMABINDING AS 
    SELECT companyid,
    CASE WHEN RTRIM(ISNULL(company,'')) <> '' AND RTRIM(ISNULL(contact,'')) <> '' THEN company +' - '+ contact
    WHEN RTRIM(ISNULL(company,'')) <> '' THEN company
    WHEN RTRIM(ISNULL(contact,'')) <> '' THEN contact
    ELSE '' END as [Name]
    FROM dbo.company


    This view can now be used everywhere the table is used, without a performance hit. Furthermore, the calculated column [Name] can actually have an index added to it! That's something you cannot do with a function.






    share|improve this answer



























      1














      What you can do is create a view that behaves like a table. Meaning it would have the performance of a table, can have indexes added etc. This view can have any of the columns of the underlying base table plus you can add calculated columns, such as [name]. This is accomplished by adding WITH SCHEMABINDING when creating the view. This view can then be used in lieu of the base table in all of your queries.



      Here is an example.
      The underlying base table with data:



      CREATE TABLE dbo.company (
      companyid int IDENTITY(1,1) NOT NULL,
      company varchar(50) NULL,
      contact varchar(50) NULL,
      CONSTRAINT PK_company PRIMARY KEY CLUSTERED (companyid ASC)
      ) ON FG1


      The view containing WITH SCHEMABINDING:



      CREATE view dbo.VW_company WITH SCHEMABINDING AS 
      SELECT companyid,
      CASE WHEN RTRIM(ISNULL(company,'')) <> '' AND RTRIM(ISNULL(contact,'')) <> '' THEN company +' - '+ contact
      WHEN RTRIM(ISNULL(company,'')) <> '' THEN company
      WHEN RTRIM(ISNULL(contact,'')) <> '' THEN contact
      ELSE '' END as [Name]
      FROM dbo.company


      This view can now be used everywhere the table is used, without a performance hit. Furthermore, the calculated column [Name] can actually have an index added to it! That's something you cannot do with a function.






      share|improve this answer

























        1












        1








        1







        What you can do is create a view that behaves like a table. Meaning it would have the performance of a table, can have indexes added etc. This view can have any of the columns of the underlying base table plus you can add calculated columns, such as [name]. This is accomplished by adding WITH SCHEMABINDING when creating the view. This view can then be used in lieu of the base table in all of your queries.



        Here is an example.
        The underlying base table with data:



        CREATE TABLE dbo.company (
        companyid int IDENTITY(1,1) NOT NULL,
        company varchar(50) NULL,
        contact varchar(50) NULL,
        CONSTRAINT PK_company PRIMARY KEY CLUSTERED (companyid ASC)
        ) ON FG1


        The view containing WITH SCHEMABINDING:



        CREATE view dbo.VW_company WITH SCHEMABINDING AS 
        SELECT companyid,
        CASE WHEN RTRIM(ISNULL(company,'')) <> '' AND RTRIM(ISNULL(contact,'')) <> '' THEN company +' - '+ contact
        WHEN RTRIM(ISNULL(company,'')) <> '' THEN company
        WHEN RTRIM(ISNULL(contact,'')) <> '' THEN contact
        ELSE '' END as [Name]
        FROM dbo.company


        This view can now be used everywhere the table is used, without a performance hit. Furthermore, the calculated column [Name] can actually have an index added to it! That's something you cannot do with a function.






        share|improve this answer













        What you can do is create a view that behaves like a table. Meaning it would have the performance of a table, can have indexes added etc. This view can have any of the columns of the underlying base table plus you can add calculated columns, such as [name]. This is accomplished by adding WITH SCHEMABINDING when creating the view. This view can then be used in lieu of the base table in all of your queries.



        Here is an example.
        The underlying base table with data:



        CREATE TABLE dbo.company (
        companyid int IDENTITY(1,1) NOT NULL,
        company varchar(50) NULL,
        contact varchar(50) NULL,
        CONSTRAINT PK_company PRIMARY KEY CLUSTERED (companyid ASC)
        ) ON FG1


        The view containing WITH SCHEMABINDING:



        CREATE view dbo.VW_company WITH SCHEMABINDING AS 
        SELECT companyid,
        CASE WHEN RTRIM(ISNULL(company,'')) <> '' AND RTRIM(ISNULL(contact,'')) <> '' THEN company +' - '+ contact
        WHEN RTRIM(ISNULL(company,'')) <> '' THEN company
        WHEN RTRIM(ISNULL(contact,'')) <> '' THEN contact
        ELSE '' END as [Name]
        FROM dbo.company


        This view can now be used everywhere the table is used, without a performance hit. Furthermore, the calculated column [Name] can actually have an index added to it! That's something you cannot do with a function.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 14 '18 at 18:29









        SteveDSteveD

        52947




        52947



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53303454%2fany-way-to-create-function-method-in-sql-for-combining-columns-in-the-select%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            這個網誌中的熱門文章

            How to read a connectionString WITH PROVIDER in .NET Core?

            Node.js Script on GitHub Pages or Amazon S3

            Museum of Modern and Contemporary Art of Trento and Rovereto