DB2 Get column with variable column name - sql

This is an off-shoot of another question I asked, with me trying to solve it myself.
I've figured out how to get the column names for the table I'm in (by querying SYSCAT.COLUMNS). I now need to someone table the value from that, and get the column with that name off of the cursor (basically, a variable column name).
For illustration, in something like JavaScript, I'd just do something like this:
const c = { COLNAME: 'myCol' };
const n = { myCol: '5' };
n[c.COLNAME]
In my cause, c is the cursor with the columns (with COLNAME the name of the column) and n is the row that has a column named the value of c.COLNAME.
If it matters, I'm doing this inside the body of a trigger.

You have to build a dynamic SQL statement...
then PREPARE and EXECUTE or EXECUTE IMMEDIATELY that statement...
As commented in your other post, this is a bad idea to do in a trigger..

Related

SQL: How to apply a function (stored procedure) within an UPDATE-clause to change values?

the following function deletes all blanks in a text or varchar column and returns the modified text/varchar as an int:
select condense_and_change_to_int(number_as_text_column) from mytable;
This exact query does work.
Though my goal is to apply this function to all rows of a column in order to consistently change its values. How would I do this? Is it possible with the UPDATE-clause, or do i need to do this within a function itself? I tried the following:
UPDATE mytable
SET column_to_be_modiefied = condense_and_change_to_int(column_to_be_modiefied);
Basically i wanted to input the value of the current row, modify it and save it to the column permanantly.
I'd welcome all ideas regarding how to solve scenarios like these. I'm working with postgresql (but welcome also more general solutions).
Is it possible with an update? Well, yes and sort-of.
From your description, the input to the function is a string of some sort. The output is a number. In general, numbers should be assigned to columns with a number type. The assumption is that the column in question is a number.
However, your update should work. The result will be a string representation of the number.
After running the update, you can change the column type, with something like:
alter table mytable alter column column_to_be_modiefied int;

SQL Server query erroring with 'An object or column name is missing or empty'

I have the following query in a stored procedure in SQL server:
SELECT TLI.LESNumber
,COUNT(TLT.PL)
INTO #PWCM
FROM #tmpLESImport TLI
INNER JOIN tbl_LES L
on TLI.LESNumber=L.NUMB
WHERE ISNULL(L.DELT_FLAG,0)=0
AND L.SCHL_PK=#SCHL_PK
AND TLI.PL IS NOT NULL
AND LEN(TLI.PL)>0
GROUP BY LESNumber
HAVING COUNT(PL)>1
When the query is run I get the following error:
An object or column name is missing or empty. For SELECT INTO statements, verify each column has a name. For other statements, look for empty alias names. Aliases defined as "" or [] are not allowed. Change the alias to a valid name.
Can anyone tell me why? #PWCM does not appear anywhere until this query.
When you SELECT INTO a table, it creates the table (in this case, a temp table). In order to create a table, each column needs a name, which your count column does not. You just need to give it a name:
SELECT TLI.LESNumber,COUNT(TLT.PL) [NumRecords]
INTO #PWCM
FROM #tmpLESImport TLI
...
I had this error for this query
SELECT
CASE WHEN COALESCE([dbo].[my-table].[field],"") = '...' THEN 'A'
WHEN COALESCE([dbo].[my-table].[field],"") = '...' THEN 'B'
...
END AS aaa INTO ##TEMPTABLE
FROM [dbo].[my-table]
Turns out I had to change the "" inside the COALSCE into ''.
Solved it for me
I just came across this, and the core reason was actually related to an errant set of brackets in the code which made the engine think there was a missing alias. Something along the lines of:
select *
from SOME_TABLE
where x = 1
[]
A stringified version of the query included a parameter list for logging, but that was being issued as the query instead of the actual query object. Deleting [] at the end resolved it.

How to select a sql table's column value by giving column index?

I have table with 3 columns. One is Id, second column is Name and the third one Description. How can I select the value in the Description field by giving the column index, 3?
Thanks in advance
You can't, from plain SQL (other than in the ORDER BY clause, which won't give you the value but will allow you to sort the result set by it).
If you are using another programming language to construct a dynamic query, you could use that to identify the column being selected by its index number.
Alternatively, you could parameterise your query to return a specific column based on a case statement - like so:
select a, b, c, d, e, ...,
case ?
when 1 then a
when 2 then b
when 3 then c
when 4 then d
when 5 then e
...
end as parameterised_column
from ...
The problem with referring to a column by an index number is that, one day, someone may add a column and break your application as the wrong value will be returned.
This principle is enforced in SQL because you can select named columns, or all columns using the * syntax.
This principle is not enforced in programming languages, where you can usually access the column by ordinal in code, but you should consider the principle before deciding to use a statement such as (psuedo code)
value = results[0].column[2].value;
It should be possible. You'd have to query the system tables (which do vary from one version of SQL to another) to get the 3rd (or Nth) column name as a string to form a following query using that column name.
In SQL 2000 the tables you'll need to start with are syscolumns with a join to sysobjects for the table name. Then the rank() function on "Colid" will give you the Nth column and "name" (shockingly) the name of the column. Once you've got that in a variable the following command can return the value, compare to it, order by it or whatever you need.
This is how you can retrieve a Column's name by passing it's index.
Here variable AcID is used as the index of the column.
Below is the code e.g
dim gFld as string
vSqlText1 = "Select * from RecMast where ID = 1000"
vSql1 = New SqlClient.SqlCommand(vSqlText1, cnnRice)
vRs1 = vSql1.ExecuteReader
if vRs1.Read then
gFld = vRs1.GetName(AcID)
msgbox gfld
end if
declare #searchIndex int
set #searchIndex = 3
select Description from tbl_name t where t.Id = #searchIndex

How to reverse data of a column into another column in MySql?

I need to run a script to update a field of a table in mysql by reversing the string stored in another field of the same table. Original column is term and the one to be filled with the reversed is revTerm. I use this, but it produce an error. Any suggestions?
UPDATE `tu_cla_terms` WHERE tId = '11583' SET revTerm = REVERSE(term)
You have the syntax of an UPDATE query wrong. SET comes before WHERE:
UPDATE `tu_cla_terms` SET revTerm = REVERSE(term) WHERE tId = '11583'
If tId is a numeric column you don't want quotes around its value either.

Dynamic Query in SQL Server

I have a table with 10 columns as col_1,col_2,.... col_10. I want to write a select statement that will select a value of one of the row and from one of these 10 columns. I have a variable that will decide which column to select from. Can such query be written where the column name is dynamically decided from a variable.
Yes, using a CASE statement:
SELECT CASE #MyVariable
WHEN 1 THEN [Col_1]
WHEN 2 THEN [Col_2]
...
WHEN 10 THEN [Col_10]
END
Whether this is a good idea is another question entirely. You should use better names than Col_1, Col_2, etc.
You could also use a string substitution method, as suggested by others. However, that is an option of last resort because it can open up your code to sql injection attacks.
Sounds like a bad, denormalized design to me.
I think a better one would have the table as parent, with rows that contain a foreign key to a separate child table that contains ten rows, one for each of those columns you have now. Let the parent table set the foreign key according to that magic value when the row is inserted or updated in the parent table.
If the child table is fairly static, this will work.
Since I don't have enough details, I can't give code. Instead, I'll explain.
Declare a string variable, something like:
declare #sql varchar(5000)
Set that variable to be the completed SQL string you want (as a string, and not actually querying... so you embed the row-name you want using string concatenation).
Then call: exec(#sql)
All set.
I assume you are running purely within Transact-SQL. What you'll need to do is dynamically create the SQL statement with your variable as the column name and use the EXECUTE command to run it. For example:
EXECUTE('select ' + #myColumn + ' from MyTable')
You can do it with a T-SQl CASE statement:
SELECT 'The result' =
CASE
WHEN choice = 1 THEN col1
WHEN choice = 2 THEN col2
...
END
FROM sometable
IMHO, Joel Coehoorn's case statement is probably the best idea
... but if you really have to use dynamic SQL, you can do it with sp_executeSQL()
I have no idea what platform you are using but you can use Dynamic LINQ pretty easily to do this.
var query = context.Table
.Where( t => t.Id == row_id )
.Select( "Col_" + column_id );
IEnumerator enumerator = query.GetEnumerator();
enumerator.MoveNext();
object columnValue = enumerator.Current;
Presumably, you'll know which actual type to cast this to depending on the column. The nice thing about this is you get the parameterized query for free, protecting you against SQL injection attacks.
This isn't something you should ever need to do if your database is correctly designed. I'd revisit the design of that element of the schema to remove the need to do this.