0

I'm using MSQL 2005. I have 2 table.A and B

Table A

- ID DOVKOD
- 1  KURSATIS

Table B

- ID KURALIS KURSATIS
- 1  2,2522  2,2685
- 2  2,4758  2,4874

Table A has only 1 record

When I execute Select (Select DOVKOD from Table A) from Table B I want to get same result as Select KURSATIS from Table B

I am gonna use it in a view. How can I do that. Thanks..

Joe Taras
  • 15,166
  • 7
  • 42
  • 55
user2170349
  • 11
  • 1
  • 3
  • 1
    Your question doesn't make much sense. Your query doesn't make much sense either. – Sean Lange Feb 19 '15 at 14:43
  • possible duplicate of [Select columns from one table based on the column names from another table](http://stackoverflow.com/questions/18702203/select-columns-from-one-table-based-on-the-column-names-from-another-table) – Tab Alleman Feb 19 '15 at 15:20

4 Answers4

1

You can simply use a CASE expression:

SELECT CASE WHEN (SELECT DOVKOD FROM A) = 'KURSATIS' THEN KURSATIS
            ELSE KURALIS
       END     
FROM B

SQL Fiddle Demo here

Giorgos Betsos
  • 71,379
  • 9
  • 63
  • 98
  • @user2170349 Happy to help, and welcome to Stack Overflow. If this answer or any other one solved your issue, please mark it as accepted. – Giorgos Betsos Feb 20 '15 at 09:40
0

The only way how to do this in MySQL is using Prepared statements. Dynamic pivot tables (transform rows to columns) is a good article about this.

SET @sql = NULL;
Select DOVKOD INTO @sql
FROM from Table A;

SET @sql = CONCAT('SELECT ', @sql, 'FROM Table B');

PREPARE stmt FROM @sql;

EXECUTE stmt;

DEALLOCATE PREPARE stmt;
mfitzp
  • 15,275
  • 7
  • 50
  • 70
Adrian Benko
  • 73
  • 1
  • 9
0

You must use Dynamic TSQL

SELECT @column=DOVKOD from Table A

EXEC ('Select ' + @column +  ' from Table B')
TLPNull
  • 475
  • 4
  • 12
0

If I understood you right then in table A you have the name of the column that you want to return. Then your solution is bad at all. I'll rather do something like that:

    CREATE TABLE #TableA
(
    ID INT, DOVKOD VARCHAR(100)
);

INSERT INTO #TableA VALUES (1, 'KURSATIS');
CREATE TABLE #TableB
(
    ID INT, Value DECIMAL (18,2),Name VARCHAR(100)
);

INSERT INTO #TableB VALUES (1, 2.2522 , 'KURALIS');
INSERT INTO #TableB VALUES (2, 2.4758 , 'KURSATIS');

SELECT #TableB.* FROM #TableB JOIN  #TableA ON #TableA.DOVKOD = #TableB.Name
Dmitrij Kultasev
  • 5,447
  • 5
  • 44
  • 88