简体   繁体   中英

Combine 2 sql query statements in to one?

Good day all. I have a statment in a Query that selects fields from a temp table and inserts it into the final table. It looks like this:

INSERT INTO [dbo].[Final]([DateStamp],[TIME],[DATE],[USER_LOGIN],[USER_NAME],[PRODUCT_NAME  ],[MODEL_NAME   ],[OPERATION    ],[CLIENT_IP    ],[OBJECT   ],[VIEW_TYPE    ],[VIEW])
SELECT CONCAT([DATE],'', [TIME]) AS [DateStamp],[TIME],[DATE],[USER_LOGIN],[USER_NAME],[PRODUCT_NAME    ],[MODEL_NAME   ],[OPERATION    ],[CLIENT_IP    ],[OBJECT   ],[VIEW_TYPE    ],[VIEW]
FROM #Temp

But after that I have to alter the final table:

UPDATE [dbo].[Final] SET [DateStamp] = SUBSTRING([DateStamp],1,10)+' '+SUBSTRING([DateStamp],11,15)
ALTER TABLE [dbo].[Final] ALTER COLUMN [DateStamp] DATETIME

Is there a way to do it in the select statement. The temp table is not being created with a DateStamp column because I am reading a text file and don't want it to start inserting data into that column. So i create it but just need to add these 2 parts together and I'm not exactly sure how to. Thanks

Yes. You can cast the value in the select . If i understand correctly:

INSERT INTO [dbo].[Final]([DateStamp],[TIME],[DATE],[USER_LOGIN],[USER_NAME],[PRODUCT_NAME  ],[MODEL_NAME   ],[OPERATION    ],[CLIENT_IP    ],[OBJECT   ],[VIEW_TYPE    ],[VIEW])
    SELECT CAST(STUFF(CONCAT([DATE],'', [TIME]), 11, 0, ' ') as DATETIME) AS [DateStamp],
           [TIME],[DATE],[USER_LOGIN],
           [USER_NAME],[PRODUCT_NAME    ],[MODEL_NAME   ],[OPERATION    ],
           [CLIENT_IP    ],[OBJECT   ],[VIEW_TYPE    ],[VIEW]
    FROM #Temp;

You could just add the date and time , if they are of the correct time.

NOTE:

I realized that you are doing insert not select into . You should set the column to the correct type. If you are using SQL Server 2012+, then use try_convert() rather than convert() to avoid errors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM