I have a question about both creating and inserting data into a table in the same time.
I have some product codes and I want to both create a table and then insert my product codes into the table. How can I do that? my product codes are integers.
We can call the table productcodes
.
5条答案
按热度按时间cotxawn71#
What you're looking for is " Select Into ".
bejyjqdl2#
The short answer is you can't without using INTO clause on your SELECT. There are potential issues dealing with nullable values and potentially the need to cast datatypes if additional records will be added later.
You can however wrap the create and insert statements into a stored procedure. Also depending on your needs you could either do a conditional create (only create the table if it doesn't exist) and append new records or a conditional delete (drop table if it exist), create table, insert records. I prefer the latter to create idempotent logic (i.e. spRecreateProductCodeLookup).
wydwbb8l3#
You could use
Table Value Constructor
to define your insert values and thenselect into
as others have mentioned to insert it directly to your table like this:Here is a demo on this: SQL Fiddle
zpgglvta4#
you could use following query example to CREATE AND INSERT in the same time SQL SERVER :
iecba09b5#
1.While creating and inserting into a table is not quite a good practice and you might not see that in real world scenarios(I haven't seen it yet). Nevertheless here is the syntax for doing so.
If you execute the above T-SQL statement as a single statement you will get something like this.Remember this will create a physical table named productcodes in the object explorer because of the
INTO
clause. Notice that I must alias theTVC (Table Valued Constructor)
just like a derived table. I also have to provide column names right after the alias.2.You can also create and insert into table without creating the physical table without the use of the
INTO
clause as below:3.You can also achieve this via a hack using the
string_split()
function.In that case, the product codes won't be integers anymore but strings. But again this is just a hack & not a good approach.