SQL Server - comparing two variables - sql-server-2008

I wish to compare a variable #a containing an entire column of a table with another variable containing a single value. Is it possible?
create procedure pc1(#var int)
as begin
declare #a int
select #a=id from tb1
while(if exists(#var=#a))
begin
select * from tb1 where id=#var
end
return
end

There is no direct way but you can do this thing in following way.
declare #a int
Set #a = 1
if exists(
select #a as ID
Intersect
Select ID
from tbl
)
Print('Hello')

Related

SELECT INTO with EXECUTE() in SQL Server

This works:
drop table #A
select v = getdate()
into #A
select * from #A
But not this (no result):
drop table #A
create table #A (v varchar(30))
declare #x varchar(30) = 'select v = getdate() into #A'
execute(#x)
select * from #A
I need to be able to do this above one to address a scenario. Must be simple and silly, but just trying to understand why this just doesn't work like first one?
Please advise. Thanks experts!
I can propose workaround and move all you script to #x variable.
So your script will be as:
declare #x nvarchar(MAX) = '
drop table IF EXISTS #A
select v=getdate() into #A
select * from #A'
PRINT(#x)
EXEC(#x)
MSDN says
SELECT…INTO creates a new table in the default filegroup and inserts the resulting rows from the query into it.
So if you create table prior to select into, you cannot use select into, you need to use insert into

MySQL stored procedure pass select as parameter

could you please give me an advice how to CALL prcd with SELECT results? Or advice me pls better solution.. I am open minded to all working solution
I have a procedure to control inserting data ...
CREATE PROCEDURE control_insert (
)
And I need to pass data from SELECT results to procedure ...
SELECT t.c1, t.c2
FROM table t1
LEFT JOIN other_table t2
ON t1.id = t2.id
WHERE 1=1
The point is, I need to get some data via SELECT (around 6 tables joined to the base table) and I need to do control for each row before insert.. each row should meet some conditions .. if it doesn't meet them, it should just skip it and process next one ...
The procedure should look like:
CREATE PROCEDURE control_insert (
IN v_c1 INT,
IN v_c2 INT
)
BEGIN
IF v_c1 > 1 THEN
INSERT INTO controlled_table (id, type) VALUES (v_c1, v_c2);
ELSE
/* do nothing */
END IF;
END;
CALL control_insert ( SELECT .... );
Could you help me with that? Is there any possibility to do this via MySQL? I can write a PERL skript, but I want to avoid this type of solution ... I just one to do it only in MySQL way
Thank you
EDIT1: I need to check if ID of the SELECT result and LABEL is already in this table for specific date ... this code above is only an example to demonstrate the situation
SOLUTION
I've found the solution ... so for the other visitors:
calling procedure:
CALL controlInsert();
procedure body:
CREATE PROCEDURE controlInsert()
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE v_id INT;
DECLARE v_id_dupl INT;
DECLARE v_label INT;
DECLARE v_date DATE;
DECLARE v_type VARCHAR(100);
DECLARE v_category VARCHAR(255);
DECLARE v_user VARCHAR(255);
DECLARE v_country VARCHAR(255);
DECLARE c1 CURSOR FOR SELECT id, label, date, type, category, user, country FROM t1 LEFT JOIN ... /* whole select with 6 joins ended by ; */
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
## open cursor
OPEN c1;
## loop through the cursor
read_loop: LOOP
## fetch cursor into variables
FETCH c1 INTO v_id , v_label, v_date, v_type, v_category, v_user, v_country;
## check if there is any record
IF done THEN
LEAVE read_loop;
END IF;
## get count of existing records
SELECT count(*) INTO v_id_dupl
FROM
WHERE 1=1
AND id = v_id
AND label= v_label
AND date = v_date;
## if v_id_dupl = 0 => no rows found (ok to load)
IF (v_id_dupl = 0) THEN
INSERT INTO target_table (id, label, date, type, category, user, country)
VALUES (v_id , v_label, v_date, v_type, v_category, v_user, v_country);
END IF;
END LOOP;
CLOSE c1;
END
If that is all your stored procedure is doing, then you don't actually need it. You can do the whole thing in a single statement:
INSERT INTO controlled_table (id, type)
SELECT t.c1, t.c2
FROM table t1
LEFT JOIN other_table t2 ON t1.id = t2.id
WHERE something = somethingElse
AND t.c1 > 1
Essentially, I've just combined your original query with the INSERT statement in your procedure.
If your procedure is more complex and needs to do multiple operations on each row, then you should look into using a cursor.

sql server stored procedure IN parameter

In SQL Server, I am passing String as parameter :
#Param1 = Test,Test1,Test2
I am formatting it to:
#Param1 = 'Test','Test1','Test2'
When I am trying to use this in SELECT statement with IN parameter, it is not returning any data
SELECT * FROM TABLE1 where COLUMN1 IN (#Param1)
What is the correct syntax?
As pointed out already in the comments by marc_s, IN requires a list of values not simply one variable.
But you could provide those values in a SELECT from a simple table variable like this:
DECLARE #Param1 TABLE (Value NVARCHAR(255));
INSERT INTO #Param1 (Value)
SELECT 'Test1'
UNION
SELECT 'Test2'
UNION
SELECT 'Test3'
SELECT
*
FROM TABLE1
WHERE
COLUMN1 IN
(SELECT Value FROM #Param1)
I wish there were array vars like that! :-)
But you can convert it to a table using a function, and then use the table with your IN clause as you're attempting.
Here is how that would look:
DECLARE #Param1 nvarchar(max)
SET #Param1 = 'Test,Test1,Test2'
SELECT *
FROM myTable
WHERE myField In (Select ParsedString From dbo.ParseStringList(#Param1))
And here is (at least one way to write) the function:
CREATE Function [dbo].[ParseStringList] (#StringArray nvarchar(max) )
Returns #tbl_string Table (ParsedString nvarchar(max)) As
BEGIN
DECLARE #end Int,
#start Int
SET #stringArray = #StringArray + ','
SET #start=1
SET #end=1
WHILE #end<Len(#StringArray)
BEGIN
SET #end = CharIndex(',', #StringArray, #end)
INSERT INTO #tbl_string
SELECT
Substring(#StringArray, #start, #end-#start)
SET #start=#end+1
SET #end = #end+1
END
RETURN
END

How to insert multiple records into a table in one stored procedure call

I have a stored procedure that accepts a string such as A, B, C...etc. I want to split the string and insert each letter as one record into a table. The result should be:
col1 col2
1 A
2 B
3 C
I could use cursor, but cursor is kind of slow if I call this stored procedure from my web page. Is there any better solution?
Instead of passing a comma-separated string, pass a table-valued parameter. First, create a table type in your database:
CREATE TYPE dbo.Strings AS TABLE(String NVARCHAR(32));
Then your stored procedure:
CREATE PROCEDURE dbo.InsertStrings
#Strings dbo.Strings READONLY
AS
BEGIN
SET NOCOUNT ON;
INSERT dbo.Table(Col2) -- assuming col1 is an IDENTITY column?
SELECT String FROM #Strings;
END
GO
Then in your C# code or whatever, you just pass a DataTable as a Structured parameter. Example here and background here.
If you really don't want to do this, because it's too hard or whatever, then you can use a much less efficient string splitting function, e.g.
CREATE FUNCTION [dbo].[SplitString]
(
#List NVARCHAR(MAX),
#Delim VARCHAR(255)
)
RETURNS TABLE
AS
RETURN ( SELECT [Value] FROM
(
SELECT
[Value] = LTRIM(RTRIM(SUBSTRING(#List, [Number],
CHARINDEX(#Delim, #List + #Delim, [Number]) - [Number])))
FROM (SELECT Number = ROW_NUMBER() OVER (ORDER BY name)
FROM sys.all_objects) AS x
WHERE Number <= LEN(#List)
AND SUBSTRING(#Delim + #List, [Number], LEN(#Delim)) = #Delim
) AS y
);
Then your procedure is:
CREATE PROCEDURE dbo.InsertStrings
#Strings NVARCHAR(MAX)
AS
BEGIN
SET NOCOUNT ON;
INSERT dbo.Table(Col2) -- assuming col1 is an IDENTITY column?
SELECT [Value] FROM dbo.SplitString(#Strings, ',');
END
GO

store SQL variable from INSERT query FROM clause result column

This is probably trivial to most of you, but I haven't been writing stored procedures for very long (6 months only). I'd like to be able to set the variable #testid based on one of the columns being used for an INSERT query. How can I do this?
DECLARE #testid INT;
INSERT INTO [exporttestresultreport] (
[testid],
[othercolumn]
)
SELECT
[testid], -- <======= how can I set my variable based on this column?
[othercolumn]
FROM
[exporttestresultreport] e
WHERE
[exporttestresultreportid] = #exporttestresultreportid
DECLARE #testid INT;
DECLARE #test TABLE (testid int);
INSERT INTO [exporttestresultreport] (
[testid],
[othercolumn]
)
OUTPUT INSERTED.testID INTO #test
SELECT
[testid], -- <======= how can I set my variable based on this column?
[othercolumn]
FROM
[exporttestresultreport] e
WHERE
[exporttestresultreportid] = #exporttestresultreportid;
SELECT #testid = testid FROM #test;
An INSERT..SELECT.. is inherently multirow so it doesn't make semse to allow assigning a value to a scalar variable: what row should be used for the value?
DECLARE #testid INT;
DECLARE #t TABLE(t INT);
INSERT exporttestresultreport
(
testid, othercolumn
)
OUTPUT INSERTED.testid INTO #t
SELECT testid, othercolumn
FROM
[exporttestresultreport] e
WHERE
[exporttestresultreportid] = #exporttestresultreportid;
SELECT #testid = t FROM #t;
-- not sure what you want to do if there are multiple rows in the insert