Store value from SELECT statement into variable on SQL Server - sql

I am trying to select value from the system object,synonyms and then store into #variable. Then I can select data from #variable without caring the server.
However it keeps saying that I need to declare scalar variable. Can anyone help?
DECLARE #variable NVARCHAR(100)
SELECT #variable = name
FROM sys.synonyms
WHERE base_object_name = '[ABC].[dbo].[tblABC]'
SELECT * FROM #variable

Your query selects all names and successively stores them in the variable, meaning that each name overwrites the previously stored name, so only the last selected name is available in the variable when the SELECT statement terminates. If you want a variable that you can query like a temporary table, you will have to declare a table variable and insert the names into that "table", afterwards you can run a select statement against that variable:
Declare #variable table (name nvarchar(128));
INSERT INTO #variable (name)
SELECT name
FROM sys.synonyms
where base_object_name = '[ABC].[dbo].[tblABC]';
select * from #variable;
But: Also on this query, the server will "care".

The problem is that you need to return only one value to the variable. In this way:
Declare #variable nvarchar(100)
#variable = (SELECT TOP(1) name -- getting only one registry
FROM sys.synonyms where base_object_name =
'[ABC].[dbo].[tblABC]')
select #variable

You have to do next :
declare #names table ( name nvarchar(100 ) );
insert #names(name)
select name
FROM sys.synonyms
where base_object_name = '[ABC].[dbo].[tblABC]';
select * from #names

Related

How do I DECLARE or SET multiple values in SQL?

Goal: Set multiple values in the DECLARE statement to use in the WHERE statement.
Issue: Cannot successfully add multiple values in the SET statement.
Example of what I’m trying to complete:
DECLARE #Beverage as varchar(1000)
SET #Beverage = (‘Water’, ‘Soda’, ‘Wine’, ‘Beer’)
SELECT Beverage
FROM ExampleServer
WHERE Beverage in (#Beverage)
Example of what currently executes correctly:
DECLARE #Beverage as varchar(1000)
SET #Beverage = (‘Water’)
SELECT Beverage
FROM ExampleServer
WHERE Beverage in (#Beverage)
A variable can hold a single scalar value, you can't assign multiple values.
If you wish to hard-code a list of values like in your question you can use a values table constructor; you can then select from your table and check with an exists correlation:
with b as (
select beverage from (values ('Water'), ('Soda'), ('Wine'), ('Beer'))b(beverage)
)
select t.Beverage
from ExampleServer t
where exists (
select * from b
where b.beverage = t.beverage
);
The above is assuming SQL Server
You can use the " EXEC (#sqlString) ". This will help you to build your SQL queries dynamically and then execute them with the command EXEC as if they are Stored procedure
DECLARE #BEVERAGE VARCHAR(200),#SQLstring VARCHAR(1000)
SET #BEVERAGE ='('+CHAR(39)+'Water'+CHAR(39)+','+CHAR(39)+'Soda'+CHAR(39)+
','+CHAR(39)+'Wine'+CHAR(39)+','+CHAR(39)+'Beer'+CHAR(39)+')'
SET #SQLstring = 'SELECT Beverage FROM ExampleServer WHERE Beverage IN
'+#BEVERAGE
--SELECT #SQLstring
EXEC (#SQLstring)
I'm using the "CHAR(39)" instead of " ' " for avoid some troubles with the string declaration
declare a variable as a temporary table :
declare #myList table (Beverage varchar(255) )
populate it with values :
insert into #myList values ("Water"), ("Soda"), ("Wine"), ("Beer")
Then you can use either the in statement :
select Beverage from ExampleServer
where Beverage in (select Beverage from #myList)

nested select query with table name in sqlite

I am trying to select all distinct values from all tables that start with a specific name, like: 'logs_2020_12_01', 'logs_2021_01_02', ..To select all tables with this specific name is straight forward:
SELECT name FROM sqlite_master WHERE type='table' AND name LIKE 'logs_%';
The select I want for one individual table is:
SELECT DISTINCT batch FROM logs_2021_01_27;
but I cannot find a way to combine it to make the selection from all tables. I tried a couple of things but it does not work, like:
SELECT DISTINCT batch FROM (SELECT name FROM sqlite_master WHERE type='table' AND name LIKE 'logs_%')
any ideas?
thanks
What about using Dynamic SQL, stored your tables information into a temp table with id column and set it to identity.
CREATE TABLE #temp ---identity column will be used to iterate
(
id INT IDENTITY,
TableName VARCHAR(20)
)
INSERT INTO #temp
SELECT name FROM sqlite_master WHERE type='table' AND name LIKE 'logs_%';
-- choose your own results with where conditions
DECLARE #SQL VARCHAR(MAX)
DECLARE #Count INT = 1
DECLARE #Table VARCHAR(20)
WHILE #COUNT <= (SELECT COUNT(*) FROM #temp)
BEGIN
select #table = TABLENAME FROM #temp WHERE id = #Count
SELECT #sql = 'SELECT DISTINCT(batch) FROM '+ #table
PRINT #SQL
SET #Count = #Count + 1
END
after your print result looks good, change it to EXEC(#SQL), thanks
SQLite does not support dynamic sql.
You have to select the column batch from each of all the tables and combine them with UNION so the duplicates are removed:
SELECT batch FROM logs_2020_12_01 UNION
SELECT batch FROM logs_2020_12_02 UNION
......................................
SELECT batch FROM logs_2020_12_30 UNION
SELECT batch FROM logs_2020_12_31
If you don't know the full names of the tables, you can get them with this statement:
SELECT name
FROM sqlite_master
WHERE type = 'table' AND name LIKE 'logs/_%' ESCAPE '/'
and then use a programming language to construct a SELECT statement with UNION to get the results that you want.

Nested update SQL Server and SELECT

I need to have a query as below:
SELECT top (1) #AddressRepeatNum=a.CheckNumber FROM(
UPDATE dbo.SearchList SET CheckNumber=CheckNumber+1
OUTPUT inserted.CheckNumber AS CheckNumber
WHERE PageAddress=#Address and CheckNumber<6
) as a
but it doesn't work. How should I rewrite it to work?
In a simple word, I want to add one to a column of my table and then if it was larger than 5 then do something
You cannot do a select directly on an update like that. You insert the output information to a table variable and then you select from the table variable.
DECLARE #AddressRepeatNum INT, #Address varchar (500) = 'Test'
DECLARE #Check table (checknumber INT)
UPDATE dbo.SearchList SET CheckNumber=CheckNumber+1
OUTPUT inserted.CheckNumber into #Check
WHERE PageAddress=#Address and CheckNumber<6
SELECT TOP (1) #AddressRepeatNum=CheckNumber
FROM #check
ORDER BY CheckNumber

sql server store the result of a select in a variable?

I am making a function. A select statement returns only one row with one column, say an int. How do i store this int inside a declared variable so that my function can return the variable ?
select sum(table_name.col1) -- this line returns only one int. How to store that
--in a declared variable ?
from
(select
col1, col2
--code here
)table_name
DECLARE #Varname int
SELECT #Varname = SUM(table_name.col1) FROM etc
SELECT #Varname
DECLARE #result INT
SELECT #result = sum(table_name.col1)
from
(select
col1, col2
--code here
)table_name

How to get values from query to a variable

According to my research, in MSSQL there is not array varible, isn't it?
I want to get the result of a select query. Query returned more than 1 value. (You can see the query below, it returned more than 1 value and I cannot assign it.)
Declare #sp_name varchar(100)
set #sp_name = (select name from sys.procedures)
Are there any way to get the result to a variable?
You can use a table variable:
declare #results table (Name nvarchar(100))
insert into #results select name from sys.procedures
select * from #results
Use this
set #sp_name = ''
select #sp_name = #sp_name +name+',' from sys.procedures
set #sp_name = left(#sp_name,len(#sp_name)-1) -- Remove last comma
Now #sp_name will be a comma separated list.
You can also do
select #sp_name into #tmpList FROM sys.procedures
select * from #tmpList
You are right, no arrays, but hopefully either the comma list or temp table will do what you want..