SQL Server execute stored procedure in update statement - sql

every updated record must have different value by using a procedure
the procedure returns single integer value
declare #value int;
exec #value = get_proc param;
update table1 set field1 = #value;
this will work for one record but i want the procedure to get new value for each record

Just a quick example of how to use a TVF to perform this type of update:
USE tempdb;
GO
CREATE TABLE dbo.Table1(ID INT, Column1 INT);
INSERT dbo.Table1(ID)
SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3;
GO
CREATE FUNCTION dbo.CalculateNewValue
(#ID INT)
RETURNS TABLE
AS
-- no idea what this logic would be,
-- just showing an example
RETURN(SELECT NewValue = #ID + 1);
GO
SELECT t1.ID, n.NewValue
FROM dbo.Table1 AS t1
CROSS APPLY dbo.CalculateNewValue(t1.ID) AS n;
Results:
ID NewValue
-- --------
1 2
2 3
3 4
Now an update that uses the same information:
UPDATE t1 SET Column1 = n.NewValue
FROM dbo.Table1 AS t1
CROSS APPLY dbo.CalculateNewValue(t1.ID) AS n;
SELECT ID, Column1 FROM dbo.Table1;
Results:
ID Column1
-- -------
1 2
2 3
3 4

Does it really need to be a procedure ? If you can implement get_proc as function, then you can apply it on every record that you want ;)
Also, what are you using value1 for ? In the example that you've provided, it's not needed.

Related

Update a column with the result-dataset-count of a stored procedure

I have a table #data which has the columns Id and Count. In addition I have a stored procedure MyProc which accepts a parameter #id (equals the Id column) and returns a dataset (the count equals the Count column).
My goal is to assign the Count column from Id with MyProc without a cursor.
I know, something like this does not work:
UPDATE d
SET Count = (SELECT COUNT(*) FROM (EXEC MyProc d.Id))
FROM #data AS d
Is there a syntax I do not know or is a cursor the only option to achieve this?
PS: It is a code quality and performance problem for me. Calling the stored procedure would be the easiest way without repeating 50 lines of SQL but a cursor slows it down.
I believe you can make use of the below query :
IF OBJECT_ID('dbo.data') IS NOT NULL DROP TABLE data;
IF OBJECT_ID('dbo.MyFunct') IS NOT NULL DROP FUNCTION dbo.MyFunct;
GO
CREATE TABLE data
(
ID int,
[Count] int
);
INSERT data VALUES (1,5), (1,10), (2,3), (4,6);
GO
UPDATE d
SET d.[Count] = f.CNT
FROM
(SELECT ID,COUNT(id) AS CNT FROM data GROUP BY ID) f
INNER JOIN data d ON f.ID = d.ID
I couldn't find a way to use Stored procedure. Needed you can use Table valued function:
CREATE FUNCTION dbo.MyFunct(#id INT)
RETURNS #i TABLE
(ID INT , CNT INT)
AS
BEGIN
INSERT INTO #i
SELECT ID,COUNT(id) AS CNT FROM data GROUP BY ID
RETURN
END;
GO
UPDATE d
SET d.[Count] = f.CNT
FROM dbo.MyFunct(1) f INNER JOIN data d ON f.ID = d.ID
To do what you say, you need a function, not a procedure.
CREATE FUNCTION dbo.myFunc (#Id INT)
RETURNS INT
AS
BEGIN
UPDATE someTable
SET someCol = 'someValue'
WHERE id = #Id;
RETURN ##ROWCOUNT;
END
GO
Then call the function in your update statement;
UPDATE d
SET d.Count = dbo.myFunc(d.Id)
FROM #data AS d;
However, row-based operations is bad practice. You should always strive to perform set-based operations, but as I don't know what your procedure does, I cannot provide more than a wild guess to what you should do (not using a procedure at all):
DECLARE #data TABLE (Id INT);
UPDATE x
SET x.someCol = 'SomeVal'
OUTPUT INSERTED.id INTO #data
FROM someTable AS x
INNER JOIN #data AS d
ON d.Id = x.Id;
WITH cte (Id, myCount) AS (
SELECT d.Id
,COUNT(d.Id) AS myCount
FROM #data AS d
GROUP BY d.Id
)
UPDATE d
SET d.[Count] = c.myCount
FROM #data AS d
INNER JOIN cte AS c
ON c.Id = d.Id;
I don't fully understand what you're trying to do but I think your solution will involve ##ROWCOUNT; Observe:
-- Sample data and proc...
----------------------------------------------------------------------
IF OBJECT_ID('tempdb..#data') IS NOT NULL DROP TABLE #data;
IF OBJECT_ID('dbo.MyProc') IS NOT NULL DROP PROC dbo.MyProc;
GO
CREATE TABLE #data
(
id int,
[Count] int
);
INSERT #data VALUES (1,5), (1,10), (2,3), (4,6);
GO
CREATE PROC dbo.MyProc(#id int)
AS
BEGIN
SELECT 'some value'
FROM #data
WHERE #id = id;
END;
GO
Data BEFORE:
id Count
----------- -----------
1 5
1 10
2 3
4 6
A routine that uses ##ROWCOUNT
DECLARE #someid int = 1; -- the value you're passing to your proc
EXEC dbo.MyProc 1;
DECLARE #rows int = ##ROWCOUNT; -- this is what you need.
UPDATE #data
SET [Count] = #rows
WHERE id = #someid;
Data AFTER
id Count
----------- -----------
1 2
1 2
2 3
4 6

Sorting results of SQL query just like IN parameter list

I'm doing a query which looks something like
SELECT id,name FROM table WHERE id IN (2,1,4,3)
I'd like to get
id name
2 B
1 A
4 D
3 C
but I'm getting
1 A
2 B
3 C
4 D
Is there any way to sort the query results in the same way as the list I'm including after IN?
Believe me, I have a practical reason that I would need it for ;)
SELECT id,name FROM table WHERE id IN (2,1,4,3)
ORDER BY CASE id
WHEN 2 THEN 1
WHEN 1 THEN 2
WHEN 4 THEN 3
WHEN 3 THEN 4
ELSE 5
END
This might solve your problem.
Solution 2, insert your list into a temp table and get them a running sequence
id, seq(+1 every new row added)
-----------------
2 1
1 2
4 3
3 4
then join 2 table together and order by this seq.
Okay, I did it myself. It's a bit mad but it works ;)
DECLARE #IDs varchar(max)
DECLARE #nr int
DECLARE #znak varchar(1)
DECLARE #index int
DECLARE #ID varchar(max)
SET #IDs='7002,7001,7004,7003'
SET #nr=1
SET #index=1
IF OBJECT_ID('tempdb..#temp') IS NOT NULL DROP TABLE #temp
CREATE TABLE #temp (nr int, id int)
--fill temp table with Ids
WHILE #index<=LEN(#Ids)
BEGIN
set #znak=''
set #ID=''
WHILE #znak<>',' AND #index<=LEN(#Ids)
BEGIN
SET #znak= SUBSTRING(#IDs,#index,1)
IF #znak<>',' SET #ID=#ID+#znak
SET #index=#index+1
END
INSERT INTO #temp(nr,id) VALUES (#nr,CAST(#ID as int))
SET #nr=#nr+1
END
-- select proper data in wanted order
SELECT MyTable.* FROM MyTable
INNER JOIN #temp ON MyTable.id=#temp.id
ORDER BY #temp.nr

SQL SELECT statement, column names as values from another table

I'm working on a database which has the following table:
id location
1 Singapore
2 Vancouver
3 Egypt
4 Tibet
5 Crete
6 Monaco
My question is, how can I produce a query from this which would result in column names like the following without writing them into the query:
Query result:
Singapore , Vancouver, Egypt, Tibet, ...
< values >
how can I produce a query which would result in column names like the
following without writing them into the query:
Even with crosstab() (from the tablefunc extension), you have to spell out the column names.
Except, if you create a dedicated C function for your query. The tablefunc extension provides a framework for this, output columns (the list of countries) have to be stable, though. I wrote up a "tutorial" for a similar case a few days ago:
PostgreSQL row to columns
The alternative is to use CASE statements like this:
SELECT sum(CASE WHEN t.id = 1 THEN o.ct END) AS "Singapore"
, sum(CASE WHEN t.id = 2 THEN o.ct END) AS "Vancouver"
, sum(CASE WHEN t.id = 3 THEN o.ct END) AS "Egypt"
-- more?
FROM tbl t
JOIN (
SELECT id, count(*) AS ct
FROM other_tbl
GROUP BY id
) o USING (id);
ELSE NULL is optional in a CASE expression. The manual:
If the ELSE clause is omitted and no condition is true, the result is null.
Basics for both techniques:
PostgreSQL Crosstab Query
You could do this with some really messing dynamic sql but I wouldn't recommend it.
However you could produce something like below, let me know if that stucture is acceptable and I will post some sql.
Location | Count
---------+------
Singapore| 1
Vancouver| 0
Egypt | 2
Tibet | 1
Crete | 3
Monaco | 0
Script for SelectTopNRows command from SSMS
drop table #yourtable;
create table #yourtable(id int, location varchar(25));
insert into #yourtable values
('1','Singapore'),
('2','Vancouver'),
('3','Egypt'),
('4','Tibet'),
('5','Crete'),
('6','Monaco');
drop table #temp;
create table #temp( col1 int );
Declare #Script as Varchar(8000);
Declare #Script_prepare as Varchar(8000);
Set #Script_prepare = 'Alter table #temp Add [?] varchar(100);'
Set #Script = ''
Select
#Script = #Script + Replace(#Script_prepare, '?', [location])
From
#yourtable
Where
[id] is not null
Exec (#Script);
ALTER TABLE #temp DROP COLUMN col1 ;
select * from #temp;

IF condition in view in SQL Server

Is it possible to have a if condition in VIEWS
eg
CREATE VIEW
as
DECLARE #Count int
SET #Count=-1
select #Count=EmpID from EmployeeDetails where ID=200
IF #Count=-1
BEGIN
SELECT * FROM TEAM1
END
ELSE
BEGIN
SELECT * FROM TEAM1
END
You could try something sneaky with a UNION :
SELECT {fieldlist}
FROM Table1
WHERE EXISTS(SELECT EmpID FROM EmployeeDetails WHERE ID = 200)
UNION ALL
SELECT {fieldlist}
FROM Table2
WHERE NOT EXISTS(SELECT EmpID FROM EmployeeDetails WHERE ID = 200)
This method would require both SELECT statements to return the same set of fields, although their sources might be different.
Views only allow select statements as stated in here
if you need to do if on column values you can use a
SELECT
CASE WHEN COLUMN1 = 1 THEN COLUMNX ELSE COLUMNY END
FROM TABLE1
if your need exceeds this you should create a select from a table valued function instead of a view.
What you need is a simple Procedure
CREATE PROCEDURE DOSOMETHING
(
#ID INT
)
AS
BEGIN
IF #ID > 100
SELECT 1 AS ID,'ME' AS NAME, GETDATE() AS VARIABLEDATECOL, NEWID() AS VARIABLEGUID
ELSE
SELECT 2 AS ID, 'YOU' AS NAME
END
No I don't believe this is possible.
You could use a stored procedure instead to achieve this functionality.
simply use a udf (User defined Function)
Here you can use IF, ELSE, WHILE etc.
But when you are manipulating data (INSERT, UPDATE, DELETE) then you have to use Stored Procedures because udf's aren't able to do that

Stored procedure returning the result of an UPDATE

I have a table that is used to store an incrementing numeric ID (of type INT). It contains a single row. The ID is incremented using a query:
UPDATE TOP(1) MyTable
WITH(TABLOCKX)
SET NextID = NextID + 1
I would like to move this into a stored procedure that returns the value that was in the NextID column before it was incremented, but am unsure how to do this using OUTPUT parameters. Any help would be appreciated.
for SQL Server 2005+, try:
CREATE PROCEDURE dbo.Get_New_My_Table_ID
#current_id INT = NULL OUTPUT -- Declared OUTPUT parameter
AS
BEGIN TRANSACTION
UPDATE TOP(1) MyTable WITH(TABLOCKX)
SET NextID = NextID + 1
OUTPUT DELETED.NextID
COMMIT TRANSACTION
RETURN 0
GO
the results of OUTPUT don't need to go into an actual table, it can be a result set.
test it out:
declare #MyTable table (NextID int)
INSERT INTO #MyTable VALUES (1234)
SELECT 'BEFORE',* FROM #MyTable
PRINT '------------<<<<UPDATE>>>>---------'
UPDATE TOP(1) #MyTable
SET NextID = NextID + 1
OUTPUT DELETED.NextID
PRINT '------------<<<<UPDATE>>>>---------'
SELECT 'AFTER',* FROM #MyTable
OUTPUT:
(1 row(s) affected)
NextID
------ -----------
BEFORE 1234
(1 row(s) affected)
------------<<<<UPDATE>>>>---------
NextID
-----------
1234
(1 row(s) affected)
------------<<<<UPDATE>>>>---------
NextID
----- -----------
AFTER 1235
(1 row(s) affected)
In SQL2005 or later the previous values for updated values can be retrieved using the OUTPUT clause.
Given that only one value will be returned I don't know how this compares with Tom's approach. I suspect that Tom's will be faster as there is an extra read but no overhead of creating a table variable. (Edit: and of course mine still has to read the table variable as well!)
CREATE PROC blah
#OldId int OUTPUT
AS
DECLARE #OldIds table( NextID int);
UPDATE TOP(1) MyTable
WITH(TABLOCKX)
SET NextID = NextID + 1
OUTPUT DELETED.NextID INTO #OldIds
SELECT #OldId = NextID
FROM #OldIds
You might want to add in some error checking, etc. I also assumed that the table is a one-row table.
CREATE PROCEDURE dbo.Get_New_My_Table_ID
#current_id INT = NULL OUTPUT -- Declared OUTPUT parameter
AS
BEGIN
BEGIN TRANSACTION
SELECT
#current_id = COALESCE(next_id, 0)
FROM
dbo.My_Table WITH (TABLOCK, HOLDLOCK)
UPDATE dbo.My_Table
SET next_id = #current_id + 1
COMMIT TRANSACTION
END
GO
To use the stored procedure:
DECLARE #my_id INT
EXEC dbo.Get_New_My_Table_ID #current_id = #my_id OUTPUT