How to get save result from EXECUTE from a dynamic SQL query in another table?

Hi everyone, 
I have this query:
declare @query varchar(max) = ''
declare @par varchar(10)
SELECT @par = col1 FROM Set
declare @region varchar(50)
SELECT @region = Region FROM Customer
declare @key int
SELECT @key = CustomerKey FROM Customer
SET @query = 'SELECT CustomerKey FROM Customer where ' + @par + ' = '+ @key+ ' '
EXECUTE (@query)
With this query I want get col1 from SET and compare it to the column Region from Customer. I would like to get the matching CustomerKey for it.
After execution it says commands are executed successfully. But I want to save the result from @query in another table. I looked it up and most people say to use sp_executesql. I tried a few constructions as sampled and I would always get this error: 
Msg 214, Level 16, State 2, Procedure sp_executesql, Line 12
Procedure expects parameter '@statement' of type 'ntext/nchar/nvarchar'.
So the output should be a list of CustomerKeys in another table.
How can I save the results from EXECUTE into a variable? Then I assume I can INSERT INTO - SELECT in another table. 
Thanks

CREATE TABLE Customer
(CustomerKey INT , Name NVARCHAR(100));
GO
INSERT dbo.Customer
VALUES ( 1, N'Sam' )
GO
DECLARE @query nvarchar(max) = ''
declare @par varchar(10) = 'Name',
@key varchar(10) = 'Sam'
CREATE TABLE #temp ( CustomerKey INT );
SET @query =
insert #temp
SELECT CustomerKey
FROM Customer
where ' + @par + ' = '''+ @key+ ''' '
PRINT @query
EXEC sp_executesql @query
SELECT *
FROM #temp
DROP TABLE #temp;
DROP TABLE dbo.Customer
Cheers,
Saeid Hasani
Database Consultant
Please feel free to contact me at [email protected] as well as on Twitter and Facebook.
[My Writings on TechNet Wiki] [T-SQL Blog] [Curah!]
[Twitter] [Facebook] [Email]

Similar Messages

  • How to Get Default Value of a Data Type in SQL Query.

    Hi all,
    I am creating a procedure which will take input the table name and Column Name.
    In the Output i would like to have the data type and default value of that data type which will be used by a another procedure to blank the selected column in the database.
    I tried with SET NULL on the column but as the database is of navision the table have property set to NOT NULL.
    Here is what i have done till now.
    Create Procedure Get_Column_type
    @parm_table_name nvarchar(200),
    @parm_column_name nvarchar(20),
    @parm_result nvarchar(20)OUTPUT
    AS
    BEGIN 
    select @parm_result =
    DATA_TYPE from INFORMATION_SCHEMA.COLUMNS IC
    where TABLE_NAME = '[' + @parm_table_name +']' and COLUMN_NAME = '[' + @parm_column_name + ']'
    END
    GO
    Now instead on write a case statement for so many data types in SQL, i was thinking is it possible someway that above procedure also returns the default value which i can set in another procedure.
    Let me know if its possible or not? Thanks in advance.

    Do you looking for something like this?
    create table t10 ( c int default 1)
    SELECT so.name AS table_name, 
              sc.name AS column_name, 
              sm.text AS default_value
         FROM sys.sysobjects so
         JOIN sys.syscolumns sc ON sc.id = so.id
    LEFT JOIN sys.syscomments SM ON sm.id = sc.cdefault
        WHERE so.xtype = 'U' 
          AND SO.name = 't10'
     ORDER BY so.[name], sc.colid
    Best Regards,Uri Dimant SQL Server MVP,
    http://sqlblog.com/blogs/uri_dimant/
    MS SQL optimization: MS SQL Development and Optimization
    MS SQL Consulting:
    Large scale of database and data cleansing
    Remote DBA Services:
    Improves MS SQL Database Performance
    SQL Server Integration Services:
    Business Intelligence

  • Inserting results from select query into another table

    Hi: Is there a way to insert results returned from a SQL query into another table within the same SQL statement.
    For example
    SELECT a.SRCID,
    SUM(DECODE(a.CLASS_ID,91147,1,0)) BLOCK,
    SUM(DECODE(a.CLASS_ID,91126,1,0)) ALLOW,
    FROM EVENT_DATA a
    where
    a.class_id in (91147,91126)
    GROUP BY SRCID
    order by TOTAL DESC;The columns returned SRCID, BLOCK and ALLOW need to go into another table called AGGREGATE_COUNT. This table has fields SRCID, BLOCK and ALLOW. Or is the only way this can be done from outside of SQL like using perl or C.
    Thanks
    Ray

    INSERT INTO aggregate_count
         ( chart_id
         , srcid
         , block
         , allow
    SELECT 2234  chart_id
         , srcid
         , SUM(DECODE(class_id, 91147, 1, 0))
         , SUM(DECODE(class_id, 91126, 1, 0))
      FROM event_data
    WHERE class_id IN (91147, 91126)
    GROUP BY chart_id, srcid
    ORDER BY total DESC;

  • TS1717 How do I save my iTunes library from my windows pc to my iCloud account?

    How do I save my iTunes library from my windows pc to my iCloud account?

    You can't. iCloud does not apply to music. You will need to subscribe to iTunes Match to get music into the cloud but note that this is not a back up service.
    jim

  • I broke my iPhone 5 now using a 4 but don't know if or how to get my photos ect..from the 5 to the 4.can I do this and how plse help

    I broke my iPhone 5 now using a 4 but don't know if or how to get my photos ect..from the 5 to the 4.can I do this and how plse help

    Restore the backup of your iPhone 5 to your iPhone 4.  It will contain your camera roll photos. 
    To do this, first make sure the iPhone 4 is running the same or higher version of iOS as your iPhone 5 was.  If it isn't, you'll need to update it first.  Then, to restore the iCloud backup, you'll have to begin by erasing the iPhone 4.  If you have any newer data on the iPhone 4 that is not contained in the iPhone 5 backup, you'll need to save that first.  When you're ready, go to Settings>General>Reset, tap Erase All Content and Settings, then go through the set screens on the iPhone 4 and when given the option, choose Restore from iCloud backup and follow the prompt, choosing the backup of your iPhone 5 to restore to.  Be sure it is connected to wifi and your charger as it is restoring the backup.

  • How to get rid of compound information from nodes

    Hi expert,
           I have a hierarchy used for cost center in the report, when displaying cost center, its compound 'controlling area' is also displaying. such as for a node, its key value is 'CM01FIAC_FR_EA', in wich 'CM01' is for controlling area. I am trying to remove controlling area from display of cost center.
           for cost center, I have removed its compound from displaying by adding controlling area into row and setting it as 'no display', but for nodes of cost center hierarchy, compounds are still ther. please tell me how to get rid of compound information from nodes?
    Many Thanks,

    Hi Phani,
          cost center is displayed in hierarchy, I have remove compound from leaf of hierarchy, but compound is still there in nodes. also eventhough I set suppress result for controlling area, its result is still in the report. so you reference does not resolve my problem.
    Many Thanks,

  • How to get the week start date from ISO week number

    Hi,
    I have a table with the following stucture
    Year    error    Week1     week2   week3 ......week53
    2012       error1     2           4         2             1
    2012       error2    3          0        1                 1I was hoping to get something like select year, error, week1||'Week start date which is a monday of that week' , week2||'Week start date,again monday',....week53 from table
    Any suggestions please?
    Thanks,
    Sun

    Hi, Sun,
    To see when week N started, add 7 * (N - 1) days to the beginning of the year. (By definition, the beginning of the ISO year is the start of week 1 of the ISO year.)
    To see when week 22 of the current year started:
    SELECT  TRUNC (SYSDATE, 'IYYY') + (7 * (22 - 1))
    FROM    dual
    I hope this answers your question.
    If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all the tables involved, and the results you want from that data.
    Explain, using specific examples, how you get those results from that data.
    Always say what version of Oracle you're using.
    See the forum FAQ {message:id=9360002}

  • How to get rid of the other from the MacBook Air Memory?

    How to get rid of the other from the MacBook Air Memory? I reviewed my newly purchased MBA ear;y 2014 i7 8GB RAM and there was 24+ GB of "Other". I have Yosemite. I have restored to factory with no luck. is there a memory cleaner or process to eliminate what is not needed in Other? I know some files there are settings, and such but not 24+ GB worth is such of stuff.

    About “Other”:
    http://support.apple.com/en-us/HT202867
    Go step by step and test.
    1. Start up in Safe Mode.
        http://support.apple.com/kb/PH11212
    2. Backup your computer.
    3. Empty Trash.
       http://support.apple.com/kb/PH13806
    4. Disk space / Time Machine ?/ Local Snapshots
      Local backups
       http://support.apple.com/kb/ht4878
    5. Delete old iOS Devices Backup.
        iTunes > Preferences > Devices
        Highlight the old Backups , press “Delete Backup” and then “OK”.
        http://support.apple.com/kb/HT4946?viewlocale=en_US&locale=en_US
    6. Re-index Macintosh HD.
        This will take a while. Wait until it is finished.
        System Preferences > Spotlight > Privacy
        http://support.apple.com/kb/ht2409
    7.Try OmniDiskSweeper. This will give the storage size details of the items.
       https://www.omnigroup.com/more
       Select Macintosh HD and click  “Sweep Selected Drive” at the bottom.
       Be careful. Delete only the files that can be safely  deleted. If you are not sure about any file, don’t touch it.
    8. Move iTunes, iPhoto and iMovie media folders to an external drive.
        iTunes
        http://support.apple.com/en-us/HT201562
        iPhoto
        http://support.apple.com/kb/PH2506
        iMovie
        http://support.apple.com/kb/ph2289

  • HT1349 How do I save my purchased music from Itunes to a external hard drive so I dont lose it?

    How do I save my purchased music from Itunes to a external hard drive so I dont lose it?

    Right-click(Windows) or control-click(Mac) any item in the iTunes library other than a rented movie, reveal it in the Windows Explorer or Finder, and navigate up the folder hierarchy.
    (63453)

  • How do I save an edited photo from an album in the same album?

    How do I save an edited photo from an album in the same album in ipad?

    You mean in the organizer? Go back to the edtior and save the way you would in any program (ctrl+S/command+S or File>Save) and close the image there.

  • How do i save a pdf file from an incoming email on my ipad 2

    how do i save a pdf file from an incoming email on my ipad 2

    If you have iBooks on your iPad you have the option to save it to that. Just tap and hold on the document link and the options will pop up. Hit "open with ibooks" and it will save it in there for you. Thats one option

  • How do I save an HDR image from Nik silver FX to a jpg in photoshop?

    How do I save an HDR image from silver FX to a jpg in photoshop. when I go to file - save as then option of a jpg does not come up?

    Since the hdr image is probably 32 bits/Channel, you would need to go to Image>Mode and choose either 16 or 8 bits/channel.
    Then in the HDR Toning dialog use the Exposure and Gamma Method with the Exposure set to Zero and Gamma set to One.
    Then you should be able to save out your image as a jpeg.

  • HT1473 how do i save an audio file from a webpage to iTunes?

    how do i save an audio file from a webpage to iTunes?

    If the web page is designed to let you save files it will often have a download link, or if it is a link to the file directly you can try to right click on the file.  If it isn't set up that way then they probably don't intend for the file to be downloaded.

  • How can I save adobe reader file from gmail into my adobe reader app?? i would like to open one file in place where I'm not able to access internet and for that reason i would like to save it. is that even possible?

    How can i save adobe reader file from my gmail into my adobe reader application. or is there any other way i can save it into my phone so I'm able to open in any situation not just from my gmail???

    Long hold on the document in mail and it should give you the open in... option, select adobe reader and the file is now saved locally for viewing even while offline.

  • How to get the backup of photos from  i cloud id ?

    plz provide me the answers as soon as possible.

    BALAJI_PRASANNA wrote:
    Hello,
    I am very new to Labview. Í have an image of an LED and wanted to find the luminance value. I got the luminance image from the IMAQ ExtractSingleColorPlane but the value is not displaying. I just wanted to know how to get the value of luminance from the IMAQ ExtractSingleColorPlane. I have attached what i have done below.
    Thanks in advance.
    Before learning about LabVIEW, learn about images.  An Image (in LabVIEW) is a "representation of an image", that is, the wire itself doesn't really have a "value", but "points to" a collection of data that can be "imaged" (i.e. looked at as through it were a picture), "manipulated" (for example, extracting a color plane, basically getting the "red channel", an image looking as through it were viewed through a red filter), and possibly returning arrays of numbers representing the intensity of the light at a certain position in the picture.  
    BS

Maybe you are looking for