SQL:为本地字符串变量运行选择语句 [英] SQL : Running select statement for local string variable

查看:24
本文介绍了SQL:为本地字符串变量运行选择语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是我在 local string 上运行 SQL select 语句 的情况.如果我为我的表运行正常的选择查询,那么它就可以工作了.

Here is a case where I am running SQL select statement on local string. If I run normal select query for my tables then it works.

select * from tablesname 

但如果我有以下情况:

declare @string nvarchar(400)

set @string = N'from tablesname'

现在,如果我运行 select * from @string ,它不会按预期工作.

Now if I run select * from @string , it is not working as expected.

请建议我解决这个问题,因为我只想以这种方式运行 select 语句.如果我应该尝试其他方式,然后建议我.

Please suggest me for to resolve this problem, since I want to run the select statement in this way only. If I should try some other way, then suggest me that.

谢谢,陶西夫.

推荐答案

假设您正在使用 MySQL,因为您的问题是用它标记的,尽管这个 set @string = N'from tablesname' 建议,您正在使用 MS SQL Server 或其他东西:

Assuming you are using MySQL since your question is tagged with it, although this set @string = N'from tablesname' suggests, that you're using MS SQL Server or something:

SET @yourDynamicTablename = 'yourTable';
SET @sql = CONCAT('SELECT * FROM ', @yourDynamicTablename );
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

你可能想把它放在一个存储过程中.

You might want to put that in a stored procedure.

您的尝试无效,因为您无法从字符串中进行选择.要进一步阅读对避免 SQL 注入攻击也很有用的准备好的语句,请查看 手册.

Your attempt wasn't working, because you can't select from a string. For further reading about prepared statements, which are also useful for avoiding SQL injection attacks, have a look in the manual.

这篇关于SQL:为本地字符串变量运行选择语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆