Insert statement inside CASE WHEN - sql-server

How do I use the INSERT statement inside a CASE WHEN statement?
Here's a sample code:
select case when SOME_CONDITION then
(insert into TABLE2(column1,column2) select * from TABLE1 end)
from TABLE1

You should apply the restriction logic to the WHERE clause of the SELECT:
INSERT INTO TABLE2 (column1, column2)
SELECT * FROM TABLE1
WHERE <some condition>;
Depending on the logic of the WHERE clause, only certain records would be targeted for insertion.

Your base statement is to insert into a table selecting from other table
base on a case select statement if i did understand your question !
you can try to manipulate it using this query even if i'm not realy fan of it
try to understand what you need to do and retourn it into an SQL language addaptable
the bigest work is to understand what you want and turn it to an SQL statement that SQL server understand
with CTP as (select *
from table1
where <'the condition that you want on the case statement'>
)
insert into TABLE2(column1,column2)
select column1,column2
from table1
where id in (select id from CTP)

Related

SQL Server loop programming

For Sql Server 2014, what syntax do I need, if this is even possible?
(in pseudo-code)
DECLARE #searchstring nvarchar(20)
LOOP #searchstringstring = (SELECT keyword FROM table1)
SELECT column FROM table2 where column LIKE '%#searchstring%'
END LOOP
I want it to return all columns in a single table.
Unless I'm missing something, you want to select all the values in table2.Column that contains the text in table2.Keyword. This can be done easily with a simple inner join:
SELECT t2.column
FROM table2 t2
INNER JOIN table1 t1 ON(t2.column LIKE '%'+ t1.keyword +'%'
Sql works best with set based operations. looping is rarely the desired approach.

Output insert and table values when doing insert into

I'm inserting into a table in MS SQL Server 2008 (it's rather a copy of values from the same table) and want to get the output values for the insert. I want to get the id value of the select statement (t.id in the example below), the INSERTED.id works just fine
create table tmp.tbl_inserted (fromId int, toId int)
INSERT INTO mytable (name)
OUTPUT t.id, INSERTED.id INTO tmp.tbl_inserted
SELECT t.name FROM mytable t
Thanks in advance
You can't do it directly from an INSERT:
from_table_name
Is a column prefix that specifies a table included in the FROM clause of a DELETE, UPDATE, or MERGE statement that is used to specify the rows to update or delete.
Note that INSERT isn't mentioned.
What you have to do instead is cheat and use a MERGE:
MERGE INTO mytable m
USING (name,id FROM mytable) t ON 1=0
WHEN NOT MATCHED THEN INSERT (name) VALUES (t.name)
OUTPUT t.id, INSERTED.id INTO tmp.SizeCurveGroup_inserted
;

How to use a select query inside an insert query in SQL Server 2005

I need to insert values into a table. But my condition is that I need to select Min(date) from another table and this value should be inserted into another table.
My query
Insert into tempTable values
('Value1','Value2','Value3',(select min(val_dt) from anotherTable),'Y',getdate())
If I use this query I am facing error.
Guide me how to use select query inside the insert query.
Instead of using VALUES() in the INSERT statement, use a SELECT to add the row values:
INSERT INTO tempTable
SELECT 'Value1', 'Value2', 'Value3', MIN(val_dt), 'Y', GETDATE()
FROM anotherTable
And the SELECT statement can be as convoluted as you want, meaning WHEREs and the like can be included.

how to do an insert statement using a non auto increment ID?

The same question has been asked for MySQL here, anyway that syntax doesn't work in SQL Server.
I paste the sample from that question (by simplifying it) here because it explains what I need very well.
DECLARE #t1 integer
SET #t1=0;
-- MyTable is a simple Table with 2 fields "MyID" and "MyValue"
insert into MyTable
SELECT #t1 := #t1+1, --this "should" work in MySQL
MyAnotherValue
FROM AnotherTable
Is there a way to achieve the same in SQL Server (without using a cursor)?
Note: this is a to be run once query, it is a maintenance query, so race conditions and locks are not an issue.
This will work, even if you run it more than once:
insert into MyTable(MyId, MyValue)
select (select isnull(max(MyId), 0) from MyTable) + -- avoid duplicated keys, if you repeat this insert again
row_number() over(order by MyAnotherValue),
MyAnotherValue
from AnotherTable
The isnull() function covers the case when MyTable is empty
You can achieve this by using Row_Number()
Insert Into dbo.AnotherTable (Col1, Col2)
Select Row_Number() Over(Order By SomeColumn),
SomeColumn
From dbo.YourTable

Updating table based on Select query in stored procedure / ColdFusion

I am using ColdFusion for for a project and I have a written a query which I think can be faster using a stored procedure, but I not a T-SQL person, so I am not sure how to do it to compare.
I am running an initial query which selects a number of fields from a table based on a dynamically built cfquery. I think I know how to convert this query into the SQL Server stored procedure.
However, directly after that, I then take all of the primary key IDs from that query and run another query against a separate table that "locks" records with those IDs. The lock is a bit field (a flag) in the second table that tells the system that this record is "checked out". I have wrapped both queries in a cftransaction so that they execute as a unit.
Code Overview:
<cftransaction>
<cfquery name="selectQuery">
SELECT id, field2, field3
FROM table1
WHERE (bunch of conditions here)
</cfquery>
<cfquery name="updateQuery">
UPDATE table2
SET lockField = 1
WHERE table2.id IN (#ValueList(selectQuery.id#)
</cfquery>
</cftransaction>
I then return the selectQuery resultset to my app which uses it for outputting some data. How would I accomplish the same thing in a single SQL Server 2008 stored procedure that I could call using cfstoredproc?
Again, I am thinking that the native CF way (with cfquery) is not as efficient as a stored procedure since I have to retrieve the resultset back to CF, then call another query back to the DB. A single stored procedure does everything in the DB and then returns the original query resultset for use.
Any ideas?
You could add an OUTPUT clause to the UPDATE statement to capture the id's of the records updated and insert them into a table variable/temp table. Then JOIN back to table1 to return the result set.
DECLARE #UpdatedRecords TABLE ( ID INT )
UPDATE t2
SET t2.lockField = 1
OUTPUT Inserted.ID INTO #UpdatedRecords ( ID )
FROM table2 t2 INNER JOIN table1 t1 ON t2.id = t1.id
WHERE (bunch of conditions for table1 here)
SELECT t1.id, t1.field2, t1.field3
FROM table1 t1 INNER JOIN #UpdatedRecords u ON t1.id = u.id
Keep in mind that if table1 is in constant flux, the other values ("field2" and "field3") are not guaranteed to be what they were when the UPDATE occurred. But I think your current method is susceptible to that issue as well.
Your problem is "bunch of conditions here". Are those conditions always static? So is it ALWAYS: (FOO = #x AND BAR = #y)? Or is it conditional where sometimes FOO does not exist at all as a condition?
If FOO is not always present then you have a problem with the stored proc. T-SQL cannot do dynamic query building, in fact even allowing it would kind of negate the point of the proc, which is to compile and pre-optimize the SQL. You CAN do it of course, but you end up just having to build a SQL string inside the proc body and then executing it at the end. You're much better off using CFQuery with cfqueryparams. Actually have you considered doing this instead?
<cfquery name="updateQuery">
UPDATE table2
SET lockField = 1
WHERE table2.id IN (SELECT id
FROM table1
WHERE (bunch of conditions here))
</cfquery>
You could do your update in one query by making your first query a subquery and then using a separate statement to return your results. The whole thing could be a single stored procedure:
CREATE PROCEDURE myUpdate
#Variable [datatype], etc...
AS
BEGIN
UPDATE table2
SET lockField = 1
WHERE table2.id IN (
SELECT id
FROM table1
WHERE (bunch of conditions here)
)
SELECT id, field2, field3
FROM table1
WHERE (bunch of conditions here)
END
You'll probably have to pass some parameters in, but that's the basic structure of a stored procedure. Then you can call it from ColdFusion like so:
<cfstoredproc procedure="myUpdate">
<cfprocparam type="[CF SQL Type]" value="[CF Variable]">
etc...
<cfprocresult name="selectQuery" resultSet="1">
</cfstoredproc>
You could use those query results just like you were using them before.
No need for a SPROC.
UPDATE table2
SET table2.lockField = 1
FROM table1
WHERE table1.id = table2.id
AND table1.field2 = <cfqueryparam ....>
AND table1.field3 = <cfqueryparam ....>

Resources