Sql: Query returns column name instead of Value

Smit Patel

I have structure like this to use a Dynamic column name in After Update trigger

this two query returns ColumnName instead of Value by this statement,

(select @Name from deleted)
(select @Name from inserted)

How can i get the value from this and then store into variable?

ALTER TRIGGER [dbo].[afterUpdate_Project] ON [dbo].[Projects]
FOR UPDATE 
as 
begin

SET NOCOUNT ON;

DECLARE @ModifiedBy int = (select IsNULL(LastModifiedBy,0) from inserted)


 DECLARE @Name varchar(MAX)
 DECLARE my_Cursor CURSOR FOR 
 (
    select C.name from sys.tables T
    inner join sys.columns C on
    T.object_id = C.object_id
    where T.name = 'Projects'
 )

 OPEN my_Cursor; 

 FETCH NEXT FROM my_Cursor into @Name;

    WHILE @@FETCH_STATUS = 0 
    BEGIN
        DECLARE @OldValue nvarchar(MAX) = (select @Name from deleted)
        DECLARE @NewValue nvarchar(MAX) = (select @Name from inserted)
        print  @OldValue
        print  @NewValue

            If (@OldValue <> @NewValue)
                BEGIN
                    insert into EntityHistory 
                    values(1, @Name, @OldValue, @NewValue, @ModifiedBy, GETDATE())  
                END

    FETCH NEXT FROM my_Cursor into @Name;
    END

 CLOSE my_Cursor; DEALLOCATE my_Cursor;
 END
Chetan Ranpariya

Finally I as able to find a solution for your problem. It involves temp tables. Using temp tables excessively is not recommended but I could not figure out better solution than that.

Following is the ALTER TRIGGER script I created and it worked perfectly for my table.

ALTER TRIGGER [dbo].[afterUpdate_Project] ON [dbo].[Projects]
FOR UPDATE 
AS 
BEGIN

    SET NOCOUNT ON;

    DECLARE @ModifiedBy NVARCHAR(255) = (SELECT IsNULL(UserId,0) FROM inserted)

    DECLARE @queryForInserted NVARCHAR(255)
    DECLARE @queryForDeleted NVARCHAR(255)

    DECLARE @Name varchar(MAX)
    DECLARE my_Cursor CURSOR FOR 
    (
        SELECT C.name FROM sys.objects T
        INNER JOIN sys.columns C ON
        T.object_id = C.object_id
        WHERE T.name = 'Projects'
    )

    --Creating Temp table for storing single value for each of the column during iteration.
    IF OBJECT_ID('tempdb..#tmpInsertedSingleValue') IS NULL CREATE TABLE #tmpInsertedSingleValue(InsertedValue NVARCHAR(MAX))

    IF OBJECT_ID('tempdb..#tmpDeletedSingleValue') IS NULL CREATE TABLE #tmpDeletedSingleValue(DeletedValue NVARCHAR(MAX))

    --Creating temp tables and populating them with data from 'inserted' and 'deleted'
    SELECT TOP 1 * INTO #tmpInserted FROM inserted

    SELECT TOP 1 * INTO #tmpDeleted FROM deleted

    OPEN my_Cursor; 

    FETCH NEXT FROM my_Cursor into @Name;

        WHILE @@FETCH_STATUS = 0 
        BEGIN

            PRINT @Name

            -- Creating dynamic sql to select single column value from temp table.
            SET @queryForDeleted = 'SELECT ' + @Name + ' FROM #tmpDeleted'
            SET @queryForInserted = 'SELECT ' + @Name + ' FROM #tmpInserted'

            -- Executing dynamic sql to populabe single column value to other temp table.
            INSERT INTO #tmpDeletedSingleValue EXECUTE (@queryForDeleted)
            INSERT INTO #tmpInsertedSingleValue EXECUTE (@queryForInserted)

            -- Selecting single value in to variables.
            DECLARE @OldValue NVARCHAR(MAX) = (SELECT TOP 1 * FROM #tmpDeletedSingleValue)
            DECLARE @NewValue NVARCHAR(MAX) = (SELECT TOP 1 * FROM #tmpInsertedSingleValue)
            PRINT  @OldValue
            PRINT  @NewValue

            IF (@OldValue <> @NewValue)
            BEGIN
                INSERT INTO EntityHistory 
            VALUES (1, @Name, @OldValue, @NewValue, @ModifiedBy, GETDATE())
            END

            --Clearing SingleValue temp tables after every iteration
            DELETE FROM #tmpDeletedSingleValue
            DELETE FROM #tmpInsertedSingleValue

        FETCH NEXT FROM my_Cursor into @Name;
        END

    CLOSE my_Cursor; DEALLOCATE my_Cursor;
    -- Clearing temp tables after looping thru all the columns
    DELETE FROM #tmpDeleted
    DELETE FROM #tmpInserted
END

This should resolve your issue.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

PHP PDO mySQL query returns column name instead of value

MySQL returns the name of the column instead of the value

SQL query returns same value in each column

sql query result returns asterisk "*" as column value

A dynamic column name with value in sql query

Query to database is not returning row value, instead is returning column name

Laravel MS SQL DB::RAW Query returns "Invalid column name"

Write SQL query that returns results for each sorted value in main column

Sqlite database returns nonexistant column name instead of exception due to bad query

SQL query with field value for left join in column name

Get column name instead of column value

Indirect expansion returns variable name instead of value

Prolog returns variable name instead of value

PDO query returns "Array" instead of value

SQL Dynamic Query Error ( Column name invalid for a value that isn't a column name )

When using DB-API substitution for the column name in select query I don't get the expected value but column name instead

SQL Join query returns null instead of names

SQL query change column name

Invalid column name in SQL query

sql query - Invalid column name

SELECT query with WHERE returns all rows when column name and value are equal

selectizeinput reading column-name instead of value

SQL: SUB-QUERY in a JOIN statement returns 'Invalid Column Name' error

how to get sql select query result as column vs value wise instead of row wise without using PIVOT

SQL query that returns specific string if column is null?

Get value of SQL column and use it as column name

Use value in table as column name in query result

Lambda function returns function name instead of value in Python

GetDetailsOf returns property name instead of value (delphi 2007)

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    pump.io port in URL

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    flutter: dropdown item programmatically unselect problem

  14. 14

    How to use merge windows unallocated space into Ubuntu using GParted?

  15. 15

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  16. 16

    Nuget add packages gives access denied errors

  17. 17

    Svchost high CPU from Microsoft.BingWeather app errors

  18. 18

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  19. 19

    12.04.3--- Dconf Editor won't show com>canonical>unity option

  20. 20

    Any way to remove trailing whitespace *FOR EDITED* lines in Eclipse [for Java]?

  21. 21

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

HotTag

Archive