将列添加到现有的sql查询中

时间:2017-07-17 21:52:45

标签: sql sql-server

我有一个现有的sql命令作为变量,我想为它添加一些生成/变量列,尝试完全连接没有条件但不成功,

动态更改sql将作为命令的输入提供。一些例子它可能是什么,答案应该适用于所有人。

sql = 'SELECT X FROM Y WHERE A = 1'
sql = '(SELECT X FROM F WHERE A = 2)'
sql = 'SELECT X FROM G WHERE B = (SELECT D FROM F WHERE B = 5)'
sql = 'SELECT X FROM H WHERE G = 0'
sql = 'SELECT X FROM P WHERE W = 2'
sql = 'SELECT X FROM Z WHERE J = 9'


SELECT NEWID(), GETDATE(), sql

INSERT INTO Foo (A, B ,C) SELECT NEWID(), GETDATE(), sql

示例结果,

enter image description here

2 个答案:

答案 0 :(得分:1)

您需要在此处使用动态查询。

DECLARE @sql varchar(max) = 'SELECT X FROM Y WHERE A = 1' -- initial input
SET @sql = 'SELECT NEWID(), GETDATE(), ' + LTRIM((SUBSTRING(@sql, 7, LEN(@sql) - 6)))
SET @sql = 'INSERT INTO Foo (A, B, C) ' + @sql 

--EXEC(@sql)
print @sql

输出(可执行查询):

INSERT INTO Foo (A, B, C) SELECT NEWID(), GETDATE(), X FROM Y WHERE A = 1

答案 1 :(得分:0)

此查询应该有效。

INSERT INTO Foo (A, B ,C) 
SELECT NEWID(),GETDATE(), X FROM Y

动态查询: -

Declare @sql varchar(max)= 'select val from sumavg'

SET @sql=REPLACE(@sql,'select','select GETDATE(), NEWID(),')
EXEC(@sql )