SELECT [...] WHERE X IN #variable [duplicate] - sql

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Parameterizing an SQL IN clause?
I have read-only access to a database which I'd like to do the following on:
DECLARE #var AS INT_COLLECTION = (1,2,3)
SELECT name,column
FROM table
WHERE column IN #var
Of course INT_COLLECTION doesn't exist, but is there something similar available in SQL Server 2008? Or another way to do this without write access to the database?

This is a pretty heavy-handed approach since you have to create a user-defined table type, but it does work:
CREATE TYPE INT_COLLECTION AS TABLE (
Value Int
);
GO
DECLARE #var AS INT_COLLECTION;
INSERT INTO #var (Value)
VALUES (1), (2), (3);
SELECT name, col
FROM YourTable
WHERE col IN (SELECT Value FROM #var)

You could do something like this:
DECLARE #var AS TABLE (IDS INT);
INSERT INTO #var VALUES (1),(2),(3);
SELECT name,column
FROM table
WHERE column IN ( SELECT IDS FROM #var)

Related

How to DECLARE variable and set values to a field in a table [duplicate]

This question already has answers here:
SQL Server store multiple values in sql variable
(7 answers)
Closed 2 months ago.
I am trying to set values but need to use a field, rather than inputting hundreds of values.
Current code:
DECLARE #variable AS VARCHAR (100)
SET #variable = 'Y'
I need to be able to use a field as the value:
SET #variable = tbl.field
I have also tried
DECLARE #variable AS table (val varchar (100))
insert into #variable (val)
(SELECT
distinct field
FROM
tbl])
select * from #variable
SELECT * FROM tbl
WHERE field = #variable
However this code simply runs both at the same time, creating two outputs, so I am missing a link here
I need to be able to run the code so that all available values are set as each option needs to be tested at once.
You declared a scalar variable. It holds only one value, and cannot hold more than one value.
In this approach, you can store multiple values.
DECLARE #variable AS TABLE(val VARCHAR(50))
INSERT INTO #variable(val) VALUES
('Y'),
('N')
SELECT * FROM #variable
As Larnu wrote, you can't assign a scalar value to hold two values.
My suggestions are using a temporary table to hold all of your values, or assign both values as one and break them with STRING_SPLIT.
For example:
DECLARE #variable VARCHAR(100) = 'Y,N'
SELECT value
FROM STRING_SPLIT(#variable, ',')
A scaler variable only can store a single value in each set/select statement.

How can I get the computed column value as an output after SQL insert? [duplicate]

This question already has answers here:
Get SQL Computed Column Inserted Value
(3 answers)
Closed 1 year ago.
I have a table definition like this:
ID int /* identity column */
SecondID nvarchar(50) /* ComputedColumn */
birthdate datet */ Simple Column */
I would like to insert values on this table and I would like to get the inserted value as output,
the first ID, I got it using the scope_identity function.
Computed Function : ID * 1000
as an example, I would like to insert these values : (1,1000,12/08/2021)
What can I get from now is only the ID,
CREATE PROCEDURE [dbo].[USER_insert]
#birthdate date,
#SecondIDOut nvarchar(50) output
Begin
AS
INSERT INTO [dbo].[User]
([birthdate])
VALUES
(#birthdate)
SET #ID = scope_identity()
/* SET #SecondIDOut = ?? what can I set here */
END
How can I get the SecondID after executing the SQL insert statement?
Use an OUTPUT clause:
DECLARE #vals TABLE (id int, secondid varchar(30));
INSERT INTO [dbo].[User] ([birthdate])
OUTPUT inserted.id, inserted.secondid INTO #vals;
VALUES
(#birthdate)
SELECT *
FROM #vals;
The last statement is just for example. You can assign the values to parameters if you prefer.

sql query to create a table at runtime and insert the values in it from the select statement from the database

what i am tryin to do is make a table(#tbl) runtime and insert the data from the select statement from the database,as what i have done so far is
declare #tbl TABLE (
Item int
)
begin
insert into #tbl values select cid from tbl_custumer where cus_ph like '%'+'987'+'%'
select * from #tbl
end
as "select cid" statement returns multiple records
I think you might want the code to look like this:
begin
declare #tbl TABLE (
Item int
);
insert into #tbl(Item)
select cid
from tbl_custumer
where cus_ph like '%'+'987'+'%';
select *
from #tbl;
end;
Notes:
The begin/end block is not really necessary, but I'm guessing you want it for other reasons (a stored procedure, if, or something similar).
The values keyword is not needed when using insert . . . select.
Use semicolons at the end of each SQL statement. Although they are optional, they make the code easier to follow.

How to manipulate comma-separated list in SQL Server

I have a list of values such as
1,2,3,4...
that will be passed into my SQL query.
I need to have these values stored in a table variable. So essentially I need something like this:
declare #t (num int)
insert into #t values (1),(2),(3),(4)...
Is it possible to do that formatting in SQL Server? (turning 1,2,3,4... into (1),(2),(3),(4)...
Note: I can not change what those values look like before they get to my SQL script; I'm stuck with that list. also it may not always be 4 values; it could 1 or more.
Edit to show what values look like: under normal circumstances, this is how it would work:
select t.pk
from a_table t
where t.pk in (#place_holder#)
#placeholder# is just a literal place holder. when some one would run the report, #placeholder# is replaced with the literal values from the filter of that report:
select t.pk
from a_table t
where t.pk in (1,2,3,4) -- or whatever the user selects
t.pk is an int
note: doing
declare #t as table (
num int
)
insert into #t values (#Placeholder#)
does not work.
Your description is a bit ridicuolus, but you might give this a try:
Whatever you mean with this
I see what your trying to say; but if I type out '#placeholder#' in the script, I'll end up with '1','2','3','4' and not '1,2,3,4'
I assume this is a string with numbers, each number between single qoutes, separated with a comma:
DECLARE #passedIn VARCHAR(100)='''1'',''2'',''3'',''4'',''5'',''6'',''7''';
SELECT #passedIn; -->: '1','2','3','4','5','6','7'
Now the variable #passedIn holds exactly what you are talking about
I'll use a dynamic SQL-Statement to insert this in a temp-table (declared table variable would not work here...)
CREATE TABLE #tmpTable(ID INT);
DECLARE #cmd VARCHAR(MAX)=
'INSERT INTO #tmpTable(ID) VALUES (' + REPLACE(SUBSTRING(#passedIn,2,LEN(#passedIn)-2),''',''','),(') + ');';
EXEC (#cmd);
SELECT * FROM #tmpTable;
GO
DROP TABLE #tmpTable;
UPDATE 1: no dynamic SQL necessary, all ad-hoc...
You can get the list of numbers as derived table in a CTE easily.
This can be used in a following statement like WHERE SomeID IN(SELECT ID FROM MyIDs) (similar to this: dynamic IN section )
WITH MyIDs(ID) AS
(
SELECT A.B.value('.','int') AS ID
FROM
(
SELECT CAST('<x>' + REPLACE(SUBSTRING(#passedIn,2,LEN(#passedIn)-2),''',''','</x><x>') + '</x>' AS XML) AS AsXml
) as tbl
CROSS APPLY tbl.AsXml.nodes('/x') AS A(B)
)
SELECT * FROM MyIDs
UPDATE 2:
And to answer your question exactly:
With this following the CTE
insert into #t(num)
SELECT ID FROM MyIDs
... you would actually get your declared table variable filled - if you need it later...

WHERE IN with a local variable [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Parameterizing an SQL IN clause?
SQL:Casting a String to IDS with IN clause
I want to use a declare local variable in a WHERE IN clause
Something like this:
TABLE XYZ
COL1 COL2
1 A
2 B
3 C
4 D
5 E
RESULT
1 A
2 B
5 E
QUERY
DECLARE #VAR VARCHAR(MAX)
SET #VAR = '1,2,5'
SELECT * FROM XYZ WHERE COL1 IN #VAR
How do I do this?
Note :
I cant have a server function
I can only create primitive value (by code) and use it with my query.
I search a way that I will only change my var and not the query itself.
my code look like:
list (dbparameter)
mylist.add ('#var','1,2,5')
commandsql.returnresult(myQueryInString,mylist)
I want to
DECLARE #var TABLE
(
value INT
)
INSERT
INTO #var
VALUES
(1), (3), (5)
/* You would need three separate inserts in 2005 */
SELECT *
FROM xyz
WHERE col1 IN
(
SELECT value
FROM #var
)
You can also write a table-valued function which splits a CSV, but if your client library supports passing table variables, this is a preferred option.
You can find the function definition in the Erlang Sommarskog's article (search for simple_intlist_to_tbl). Declare it and call like this:
DECLARE #var VARCHAR(100) = '1,3,5'
SELECT *
FROM xyz
WHERE col1 IN
(
SELECT number
FROM simple_intlist_to_tbl(#var)
)
If your query is more complex than that, you would want to materialize this list first:
DECLARE #var VARCHAR(100) = '1,3,5'
DECLARE #tvar TABLE
(
number INT
)
INSERT
INTO #tvar
SELECT number
FROM simple_intlist_to_tbl(#var)
SELECT *
FROM xyz, ... /* Other complex joins */
WHERE col1 IN
(
SELECT number
FROM #tvar
)
You need a function which splits your list into a data set (use this from Jeff Moden it works and is very fast) and then just use the IN clause on your desired column(s).