Reference a column value from a temporary table - sql

In a stored procedure I get a record from a table and insert it into a temporary table #temp.
Then in this stored procedure I would like to set a value in a column of the #temp table as follows:
declare #VarName varchar(max)
set #VarName = 'Value is ' + #temp.colname
There is an error on the last line. Of course I can get the value of #temp.varname into another variable, before setting #VarName. But I would like to know if it is possible to do it inline, without another variable name.

I think this is what you mean, but it's pretty brittle in that it assumes you will only ever have one row in #temp.
DECLARE #VarName varchar(max) = (SELECT 'Value is ' + colname FROM #temp);
Example db<>fiddle

Related

query inside the variable

Is it possible in SQL to use a variable to store query.
For example to save time when subquery is used multiple times inside the main query.
Example:
DECLARE #my_query as varchar(250) = select x from my_table where my_table = y.your_table
SELECT
a,b,c,(#my_query),d,e,f
FROM my_table_1
Is it possible in SQL to use a variable to store query.
Depend on your definition of "query". If you mean store the text which we use to execute the command, then the answer is YES. If you mean an object type query, then the answer is not - since there is no data type that fit this.
What I mean is that a variable can store a value which is string. The string can be any query command that you want. Therefore, you can store for example the text "select col1,col2 from table1".
Next you need to ask how can we use this text in order to execute it as part of a query, which is done using dynamic query.
We can execute a text of a query using the build-in stored procedure sp_executesql, which is build for such needs.
For example:
-- DECLARE VARIABLE
DECLARE #MyQuery NVARCHAR(MAX)
-- SET the value of the variable
SET #MyQuery = 'SELECT ''Yes I can'''
-- Executing a dynamic query
EXECUTE sp_executesql #MyQuery
Here is another example which look more close to your question:
-- First let's create a table
CREATE TABLE T(ID INT)
INSERT T(ID) VALUES (1),(2)
GO
-- And here is what you sked about:
-- DECLARE VARIABLE
DECLARE #MyQuery NVARCHAR(MAX)
-- SET the value of the variable
SET #MyQuery = 'select ID from T where ID = ''1'''
-- Let's combine the text to a full query now
DECLARE #FullQuery NVARCHAR(MAX)
SET #FullQuery = '
SELECT
ID,(' + #MyQuery + ')
FROM T
'
PRINT #FullQuery
-- Executing a dynamic query
EXECUTE sp_executesql #FullQuery
NOTE! Your specific sample of query will return error, which is not related to the question "Is it possible in SQL to use a variable to store query". This is a result of the "query" is not well formatted.
Important! It is HIGHLY recommended to read the document about this stored procedure and learn a bit more of the options it provides us.
https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-executesql-transact-sql?view=sql-server-ver15

How to call table variables outside stored procedure

I want to access outside the scope of a stored procedure a table variable that it defines. I have tried this one, but my case is different because my procedure receives a varchar as a parameter and then it creates a varchar that is executed, someway like this:
create procedure p_x
#Table varchar(250)
as
begin
declare #Sql varchar(450)
select #sql = 'declare ' + #Table + 'table(col1 varchar(10), col2 float, col3 float, col4 float)'
select #sql = #sql + ' insert' + #Table + ' values('a', 1,1,1)'
select #sql = #sql + ' insert' + #Table + ' values('b', 2,2,2)'
select #sql = #sql + ' select * from'
execute(#sql)
end
go
The solution the other question does is to pass as a parameter the new table to be processed. But in my case, because the code is written in a decisive part inside a varchar concatenation (and also it creates auxiliary tables concatenating at the end of the varchar #Table), I don't know what to do.
To give some context: there is this procedure that uses global temporary tables, which were called inside queries. Everything was working fine until we need to change the query to transform it into a table-valued function. The query just access the tables defined inside the procedure through global scope, but the table-valued function doesn't allow to access these global temporary tables. It seems that table variables can't be global.
In short, to change the query to a table-valued function, I need to change the procedure's temporary tables into table variables that I can access inside the table-valued function.
The big picture: 1) Today I have a query that works and this query calls a procedure.
2) I want to be able to call this query from a API without having to paste 100 lines of query
3) I received the suggestion of converting the query into a TFV
4) I did it, but it doesn't work, because TFV can't use temporary tables
5) I want a workaround to create a copy of the procedure with some minor changes that I can call from the TVF.
You cannot do this with a table variable. You can do it with a Temp Table, but table variables are automatically out of scope and inaccessible outside of the procedure that creates them.

Update Query to match string to column Name

I have the following UI on my program
Then I have a table with the following columns
What I want to do is to write a query that looks at the "Item" string on my combo box and then updates the above column, in this case Handbooks, of the table above where the Generalist name matches the column. The record should be updated every time, in other words, I want to replace the information every time.
I have no idea where to begin on this. This the query I used to create the table I want to update.
SELECT repName.Rep_Name, repName.Handbooks, repName.Leaves
FROM repName INNER JOIN
Positions ON repName.Job_Code = Positions.Job_Code
ORDER BY repName.Rep_Name
In case this helps somewhat
My first guess is, as I put on the comment above, that your design is not well.
Nonetheless if in your scenario you still need to do what you are asking, then you could use dynamic sql:
DECLARE #sqlCommand varchar(1000)
DECLARE #column varchar(50)
SET #column = 'foo'
SET #value = 'bar'
SET #sqlCommand = 'UPDATE TABLE SET ' + #column + ' = ' + #value
EXEC (#sqlCommand)
You could pass the value with parameters or whatever approach is better to your case.

How can I declare a table variable with a decimal variable as the identity seed? [duplicate]

This question already has answers here:
Programmatically set identity seed in a table variable
(3 answers)
Closed 9 years ago.
I'm using this, but I can't figure out why this doesn't work. SSMS won't give me a useful message other than syntax incorrect:
DECLARE #columnSeed DECIMAL
SELECT #columnSeed = MAX([seeded_column]) + 1 FROM [table] (nolock) WHERE [conditions]
DECLARE #Temp_Table TABLE ([seeded_column] varchar(35) IDENTITY(#columnSeed, 1), [more columns])
I want to take the maximum value from a column in one table and create a temporary table variable with an identity column seeded with that previous maximum value.
Edit: OK, after digging around for into about dynamic SQL I think I've got what should work, but it still isn't:
DECLARE #columnSeed DECIMAL
[#columnSeed set properly]
EXECUTE sp_executesql
N'DECLARE #Temp TABLE (seeded_column decimal IDENTITY(#seed, 1) NOT NULL [more columns])',
N'#seed decimal',
#seed = #columnSeed;
All the info I get now is that I've incorrect syntax near '#seed'
You can't use a variable as a seed. It is invalid syntax. The table variable is already implicitly created before the batch is executed and the variable assigned anyway.
The only way of doing this would be to concatenate the desired query and execute it. All usages of the table variable would need to be in the child scope.
DECLARE #columnSeed DECIMAL(18,0) = 10
DECLARE #sql NVARCHAR(MAX) = N'DECLARE #Temp TABLE (seeded_column decimal IDENTITY(' + CAST(#columnSeed AS NVARCHAR(19)) +', 1) NOT NULL)
INSERT INTO #Temp DEFAULT VALUES;
SELECT * FROM #Temp;'
EXECUTE sp_executesql
#sql,
N'#seed decimal',
#seed = #columnSeed;
I'm sure there is a better way of doing whatever it is you are doing anyway though.
You could just declare the table variable in the outer scope with a seed of 0 and add the desired offset to your SELECT queries from it for example.
DECLARE #columnSeed DECIMAL(18,0) = 10
DECLARE #Temp TABLE (seeded_column decimal(18,0) IDENTITY(0, 1) NOT NULL)
INSERT INTO #Temp DEFAULT VALUES;
INSERT INTO #Temp DEFAULT VALUES;
SELECT #columnSeed + seeded_column AS psuedo_seeded_column
FROM #Temp;
Though the whole need for this seems suspect. You shouldn't normally care what the IDENTITY values are. If this is to prepare data that later is inserted into the table you are calculating #columnSeed from maybe just inserting it and using the OUTPUT clause to get the ID values inserted might be more appropriate and less at risk of concurrency issues.
I think you can't use parameters in DDL. In other words, you won't be able to use #seed in the IDENTITY clause. Convert the seed to a string and shove it into your DDL manually. Something like this should work. (I don't have a SQL Server instance handy, so my apologies if there are any additional errors. The point is: Don't use parameters in DDL statements.)
DECLARE #columnSeed DECIMAL
DECLARE #sql NVARCHAR(1024)
[#columnSeed set properly]
SET #sql = N'DECLARE #Temp TABLE (seeded_column decimal IDENTITY(' || CONVERT(NVARCHAR, #seed) || N', 1) NOT NULL [more columns])';
EXECUTE sp_executesql #sql

Retrieve parameter value from parameter name as a string in SQL

I am trying to use some dynamic sql. I have generated over 100 parameters, and to speed things up I am trying to use dynamic sql to only insert values into a table that I have to based off of information retrieved from other tables. I have tried many things like adding a cast etc.
Example of what I mean:
DECLARE #var1 NVARCHAR(MAX)
-- Loop through and add various values
SET #var1 = #var1 + #parameterName
-- The parameter name is retrieved from a table that holds this information
the problem is that when I add the parameter name which would be like "#myFirstParameter" into my final expression so something like this:
DECLARE #finalString NVARCHAR(MAX)
SET #finalString = 'INSERT INTO myTableName ([myFirstParameter]) VALUES (#myFirstParameter)'
EXEC(#finalString)
The "#myFirstParameter" does not get replaced by it's value and I get the following error:
Must declare the scalar variable "#myFirstParameter".
Does anyone know of a way to go from the string name of a parameter to the actual value? I am trying to avoid hardcoding all the values and any work around I have attempted has failed and given me errors which appear to be much worse than what I have stated above.
The first way is to add the parameter's value, instead of its name, to the SQL string:
SET #finalString = 'INSERT INTO myTableName ([myFirstParameter]) VALUES (' +
#myFirstParameter + ')'
This assumes the parameter has a string value. If not, you have to cast it, like cast(#myFirstParameter as varchar(128)).
The second way is to use sp_executesql instead of exec:
exec sp_executesql
N'INSERT INTO myTableName ([myFirstParameter]) VALUES (#myFirstParameter)',
N'#myFirstParameter varchar(128)',
#myFirstParameter = #myFirstParameter;