Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. Database & SysAdmin
  3. Database
  4. MSSQL - How can I reference a column to update using a variable??

MSSQL - How can I reference a column to update using a variable??

Scheduled Pinned Locked Moved Database
questionsql-serverdesignsecurityjson
19 Posts 4 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • J JTRizos

    I agree. However, the file comes from the state and we don't control it's format. Otherwise, it would be as you describe. We currently take the file into SQL table and allow access to supervisers and managers through an ASP.NET application using a GridView which provides some functions for the user. So, it's User1 SecRole1 User1 SecRole2 User1 SecRole10 User1 SecRole23 User2 SecROle1 User2 SecRole4 User2 SecRole20 User2 SecRole100 What they want is SecRole1 SecRole2 SecRole3 SecRole4 ... SecRole10 ... SecRole20 SecRole21 SecRole22 SecRole23 ... SecRol100 User1 Y Y N N Y N N N Y N User2 Y N N Y N Y N N N Y in GridView making it easier to compare who is in a SecRole. Thanx for your response. I appreciate any feedback provided.

    P Offline
    P Offline
    PIEBALDconsult
    wrote on last edited by
    #10

    There should be no reason to store the data in the same form you receive it.

    1 Reply Last reply
    0
    • J JTRizos

      I have a table with one record per security role a user has. So, user SMITH can have multiple records, one for DMV another for CPT and another for ICD. In this example, SMITH has three security roles but can have up to 100. The desire is to have a second table with one record per user with columns for each security role indicating with Y or N whether the user has that role. The column names are the same as the security role name (eg. DMV, CPT, ICD,...) Smith would have 3 columns with a Y and all the rest with an N. So, is there a way to read in the first table, use the data in the security role field (DMV, CPT, ICD, etc) to then reference the column in the second table and update the respective column to a "Y" to indicate the user has that role? For example: if table2:ColumnName(DMV)=table1:Security Role("DMV") then update table2:Column(DMV)="Y". The key to both tables is the Employee ID. The input file we use to create table 1 is in the one record per Security Role per user design. We do not control that. The intent is to avoid long Case statements. I've Googled this multiple ways and read lots of possibilities but none seem to have a workable solution but most likely I just don't understand it. Below is one way I hoped would worked and a couple of forums indicated it would but I get 'Yes' in the @colname variable.

      Declare @colname varchar(200), @Eid varchar(50),@message varchar(80),@command varchar(200)
      Declare my_cursor CURSOR
      For Select replace(replace(replace(SecurityRole,' ',''),'/',''),'-','') as SecRole,EmployeeID
      from EmergencyContact.dbo.CSEEmployeeRoles
      where EmployeeID='38'
      order by EmployeeID, SecRole
      open my_cursor
      fetch next from my_cursor into @colname,@Eid
      while @@fetch_status = 0
      begin
      select @message = @colname+' '+@Eid
      print @message
      select @command= 'update EmergencyContact.dbo.CSERolesRolledUp set '+@colname+' = "Yes"
      where EmployeeID = '+@Eid
      exec (@command)
      fetch next from my_cursor into @colname,@Eid
      end
      close my_cursor
      deallocate my_cursor

      Any help will much appreciated. Seems so simple. :confused:

      M Offline
      M Offline
      Mycroft Holmes
      wrote on last edited by
      #11

      Both Piebald and Jorgen have essentially answered your question You MUST not store the data again (unless you are going to normalise the data as suggested by piebald) You should use a pivot query to present the data in the format the user requires. This article [^]may help (shameless plug) I would suggest that you do both, restructure the data when you receive it from the State, just b/c someone else has a crappy format (or you are actually receiving denormalised data designed for output) does not mean you can't change it in your loading process. Create a view (or at least a stored proc) based on the article that supplies the data in the format the users require. Oh and give Piebald and Jorgen an upvote for the valid answers.

      Never underestimate the power of human stupidity RAH

      J J 2 Replies Last reply
      0
      • M Mycroft Holmes

        Both Piebald and Jorgen have essentially answered your question You MUST not store the data again (unless you are going to normalise the data as suggested by piebald) You should use a pivot query to present the data in the format the user requires. This article [^]may help (shameless plug) I would suggest that you do both, restructure the data when you receive it from the State, just b/c someone else has a crappy format (or you are actually receiving denormalised data designed for output) does not mean you can't change it in your loading process. Create a view (or at least a stored proc) based on the article that supplies the data in the format the users require. Oh and give Piebald and Jorgen an upvote for the valid answers.

        Never underestimate the power of human stupidity RAH

        J Offline
        J Offline
        Jorgen Andersson
        wrote on last edited by
        #12

        Shameless plug. I think not. It totally relevant to the OP. If I hadn't forgotten that I already bookmarked it, I would have linked to it myself. :sigh: I guess that's just how bad your brain works when you're home with the flu.

        "When did ignorance become a point of view" - Dilbert

        1 Reply Last reply
        0
        • M Mycroft Holmes

          Both Piebald and Jorgen have essentially answered your question You MUST not store the data again (unless you are going to normalise the data as suggested by piebald) You should use a pivot query to present the data in the format the user requires. This article [^]may help (shameless plug) I would suggest that you do both, restructure the data when you receive it from the State, just b/c someone else has a crappy format (or you are actually receiving denormalised data designed for output) does not mean you can't change it in your loading process. Create a view (or at least a stored proc) based on the article that supplies the data in the format the users require. Oh and give Piebald and Jorgen an upvote for the valid answers.

          Never underestimate the power of human stupidity RAH

          J Offline
          J Offline
          JTRizos
          wrote on last edited by
          #13

          You are right, both their responses were very helpful and I am now working on using a Pivot to do this. Not sure yet how the end result can be used by a GridView to display the data to the user. Just opened your article and seems to be really helpful. Thanx! However, my original question had to do with using a variable to reference a column for updating. From what I've read, this should work ... as I understand it. Sadly, it does not for me. So, final question ... is this doable and if it is, what am I doing wrong? See original question and code. :confused: Thanx again and I will give upvotes to both. :thumbsup:

          modified on Tuesday, December 21, 2010 12:11 PM

          M 1 Reply Last reply
          0
          • J JTRizos

            You are right, both their responses were very helpful and I am now working on using a Pivot to do this. Not sure yet how the end result can be used by a GridView to display the data to the user. Just opened your article and seems to be really helpful. Thanx! However, my original question had to do with using a variable to reference a column for updating. From what I've read, this should work ... as I understand it. Sadly, it does not for me. So, final question ... is this doable and if it is, what am I doing wrong? See original question and code. :confused: Thanx again and I will give upvotes to both. :thumbsup:

            modified on Tuesday, December 21, 2010 12:11 PM

            M Offline
            M Offline
            Mycroft Holmes
            wrote on last edited by
            #14

            The only way to do it is the one you have used, dynamic sql.

            Never underestimate the power of human stupidity RAH

            J 1 Reply Last reply
            0
            • M Mycroft Holmes

              The only way to do it is the one you have used, dynamic sql.

              Never underestimate the power of human stupidity RAH

              J Offline
              J Offline
              JTRizos
              wrote on last edited by
              #15

              But it does not work and I am stumped. Thanx for your help. I am working through your Pivot article too see if it applies to what I am trying to do. Good article!

              M 1 Reply Last reply
              0
              • J JTRizos

                But it does not work and I am stumped. Thanx for your help. I am working through your Pivot article too see if it applies to what I am trying to do. Good article!

                M Offline
                M Offline
                Mycroft Holmes
                wrote on last edited by
                #16

                JTRizos wrote:

                select @command= 'update EmergencyContact.dbo.CSERolesRolledUp set '+@colname+' = "Yes"where EmployeeID = '+@Eid

                Print this variable and run it directly in SSMS, see if it updates, I think you problem is simply formatting the string! try changing "Yes" to 'Yes'

                Never underestimate the power of human stupidity RAH

                J 1 Reply Last reply
                0
                • M Mycroft Holmes

                  JTRizos wrote:

                  select @command= 'update EmergencyContact.dbo.CSERolesRolledUp set '+@colname+' = "Yes"where EmployeeID = '+@Eid

                  Print this variable and run it directly in SSMS, see if it updates, I think you problem is simply formatting the string! try changing "Yes" to 'Yes'

                  Never underestimate the power of human stupidity RAH

                  J Offline
                  J Offline
                  JTRizos
                  wrote on last edited by
                  #17

                  Thanx for the suggestion. Printing the variable @command displays the correct Update command: update EmergencyContact.dbo.CSERolesRolledUp set AddRequesterInformation = "Yes" where EmployeeID = 38 But I get an "Invalid column name 'Yes'" error and no update is done. Feeling a bit more reassured that this will work but need to figure out why the error. At least you did not say this would not work. Thanx again and Merry Christmas!

                  M 1 Reply Last reply
                  0
                  • J JTRizos

                    Thanx for the suggestion. Printing the variable @command displays the correct Update command: update EmergencyContact.dbo.CSERolesRolledUp set AddRequesterInformation = "Yes" where EmployeeID = 38 But I get an "Invalid column name 'Yes'" error and no update is done. Feeling a bit more reassured that this will work but need to figure out why the error. At least you did not say this would not work. Thanx again and Merry Christmas!

                    M Offline
                    M Offline
                    Mycroft Holmes
                    wrote on last edited by
                    #18

                    change the quotes around yes to single quotes '

                    Never underestimate the power of human stupidity RAH

                    J 1 Reply Last reply
                    0
                    • M Mycroft Holmes

                      change the quotes around yes to single quotes '

                      Never underestimate the power of human stupidity RAH

                      J Offline
                      J Offline
                      JTRizos
                      wrote on last edited by
                      #19

                      I got it to work. Followed your advise from your previous reply and after a few tries, bingo, it worked. Here's the code in case it can help others. I am leaving the print statements I used for testing.

                      Declare @colname varchar(200), @Eid varchar(50),@message varchar(80),@command varchar(200)
                      Declare my_cursor CURSOR

                      For Select replace(replace(replace(SecurityRole,' ',''),'/',''),'-','') as SecRole,EmployeeID
                      from EmergencyContact.dbo.CSEEmployeeRoles
                      order by EmployeeID, SecRole

                      open my_cursor

                      fetch next from my_cursor into @colname,@Eid
                      while @@fetch_status = 0
                      begin
                      select @message = @colname+' '+@Eid
                      --print @message

                      select @command= 'update EmergencyContact.dbo.CSERolesRolledUp set '+@colname+' = ''Yes''
                      where EmployeeID = '+@Eid
                      exec (@command)
                      print @UpdDate
                      --print @colname
                      --print @command
                      fetch next from my_cursor into @colname,@Eid
                      --print @colname
                      end
                      close my_cursor
                      deallocate my_cursor

                      Thanx again for your help. Having never used Cursor or Dynamic SQL before, I just needed to know it can be done and I was on the right track. Happy Holidays! :-D

                      1 Reply Last reply
                      0
                      Reply
                      • Reply as topic
                      Log in to reply
                      • Oldest to Newest
                      • Newest to Oldest
                      • Most Votes


                      • Login

                      • Don't have an account? Register

                      • Login or register to search.
                      • First post
                        Last post
                      0
                      • Categories
                      • Recent
                      • Tags
                      • Popular
                      • World
                      • Users
                      • Groups