如何将变量用作SELECT语句的列名

编程入门 行业动态 更新时间:2024-10-20 13:46:37
本文介绍了如何将变量用作SELECT语句的列名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我无法在SELECT语句中使用先前定义的表示列名称的变量,并且需要一些帮助.

表格:

main | i1 | i2 ||..........| i24 | i25 | . . 17 | 121 | 123| ......... 19 | 123 | 212| ......... | 4832 | 56392 |

来自先前的SELECT/SET语句@indent变量等于25.由于我不能使用整数作为列名,因此tableindex中的列为i1-i25.但是,当我尝试在SELECT语句中使用@VARIABLE时,会得到以下信息:

From a previous SELECT/SET statement @indent variable equaled 25. As I can't use an integer as a column name the columns are i1 - i25 in the tableindex. However when I attempt to use the @VARIABLE in the SELECT statment I get the following:

SET @colindex1=(CONCAT(i, @indent); SELECT @colindex1 FROM tableindex WHERE main=19;

结果

| @colindex1 | | i25 |

应该成为细胞的价值:

| i25 | | 56392|

因此,下一个附加操作是使用DECLARE语句.

So the next attach was to use a DECLARE statement.

DECLARE @colindex1 VARCHAR;

但是我遇到了以下错误:

But I got the following error:

错误1064(42000):您的SQL语法有错误;检查与您的MySQL服务器版本相对应的手册以获取正确的语法,以在第1行的'declare @ colindex1 INT'附近使用

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'declare @colindex1 INT' at line 1

我需要将我的整数(25)值与字母"i"组合到列"i25",然后将其用于SELECT语句.但是我在这一点上失败了.

I need to combine my integer (25) value with the letter (i) for the column "i25' and then use it a SELECT statement. However I am failing at this point.

有人可以帮忙吗

基于答案,这里是使用指定的语法和错误的测试:

BASED ON ANSWER HERE IS A TEST USING THE SPECIFIED SYNTAX AND ERROR:

SET @indent = 1+24; SET @colindent1 = (SELECT CONCAT('i', @indent)); set @stmt = (SELECT @colindent1 FROM tableindex WHERE main=19); PREPARE thestmt FROM @stmt;

错误1064(42000):..在'i25'附近的第1行AAAAHH!我在做什么错?

ERROR 1064 (42000): ..near 'i25' at line 1 AAAAHH! WHAT AM I DOING WRONG?

但是:

set @stmt = (SELECT i25 FROM tableindex WHERE main=19); Query OK, 0 rows affected (0.00 sec)

推荐答案

要使用变量表示列(或表),您需要使用PREPARE/EXECUTE. 尝试这样的事情:

To use variables to represent columns (or tables), you need to use PREPARE/EXECUTE. Try something like this:

SET @colindex1=(CONCAT(i, @indent); SET @stmt = 'SELECT @colindex1 FROM tableindex WHERE main=19'; PREPARE thestmt FROM @stmt; EXECUTE thestmt;

更多推荐

如何将变量用作SELECT语句的列名

本文发布于:2023-11-22 06:44:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1616367.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   如何将   语句   SELECT

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!