[英]Declare and use t-sql variable from java using JDBC driver
I'm trying to run this sql script from a java client on a sql server. 我正在尝试从sql服务器上的java客户端运行此sql脚本。
DECLARE @CON_NAME VARCHAR(100);
DECLARE @COMMAND VARCHAR(200);
SELECT @CON_NAME=NAME FROM sys.key_constraints WHERE [type] = 'PK' AND [parent_object_id] = Object_id('dbo.MY_TABLE');
SELECT @COMMAND=CONCAT('ALTER TABLE MY_TABLE DROP CONSTRAINT ', @CON_NAME);
SELECT @COMMAND;
EXEC (@COMMAND);
What the java client does is run the script line by line. Java客户端所做的是逐行运行脚本。
I'm getting the exception below: 我在下面遇到异常:
com.microsoft.sqlserver.jdbc.SQLServerException: Must declare the scalar variable "@CON_NAME".
How can I solve this issue? 我该如何解决这个问题?
Instead of running the script line by line, send the entire script as one statement. 而不是逐行运行脚本,而是将整个脚本作为一条语句发送。
Running each line separately, means you're running multiple scripts, like if you had put each line in a separate .sql file. 单独运行每一行,意味着您正在运行多个脚本,就像您已将每一行放在单独的.sql文件中一样。
DECLARE
'd variables are local to the script, so running the lines individually makes no sense. DECLARE
d变量在脚本中是局部的,因此单独运行这些行是没有意义的。
Must declare the scalar variable "@CON_NAME"
必须声明标量变量“ @CON_NAME”
Though guess but I think you haven't wrapped your posted SQL code in a procedure rather you are just running/calling them line by line from your java application code like a normal sql query and so the error. 虽然是猜测,但我认为您尚未将发布的SQL代码包装在过程中,而是像正常的SQL查询一样从Java应用程序代码逐行运行/调用它们,因此报错。 Cause by the time it reaches to the line where the variable is getting used that variable declaration is no more present in that scope.
由于到达变量使用行的时间导致该范围中不再存在变量声明。
You should consider put this code inside a stored procedure and call that procedure from your code behind rather. 您应该考虑将此代码放入存储过程中,然后从代码中调用该过程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.