I have got the following SQL statement (SQL Server):
DECLARE @atr nvarchar(255), @con nvarchar(1000), @func nvarchar(5);
SET @con='example'
SET @func=(SELECT FNCELEM FROM CNDSC WHERE NAME LIKE @con)
DECLARE Atr_Cursor CURSOR FOR
SELECT ATRBT FROM CNEA WHERE (ELEMS LIKE '%'+@func+'%' AND NOT ELEMS LIKE '%1' + @func + '%');
OPEN Atr_Cursor;
FETCH NEXT FROM Atr_Cursor
INTO @atr;
WHILE @@FETCH_STATUS = 0
BEGIN
DECLARE @SQLString nvarchar(500);
IF (SELECT COUNT(*) FROM CNEXTRA WHERE ATR LIKE ''+@atr+'' AND NAME LIKE ''+@con+'')>0
BEGIN
SET @SQLString= N'SELECT NAME, ATR, CNVAL, INRDR FROM CNEXTRA WHERE ATR LIKE ''' + @atr + ''' AND NAME LIKE '''+@con+''';';
END
ELSE
BEGIN
SET @SQLString= N'SELECT '''+@con+''' AS NAME, '''+@atr+''' AS ATR, '''' AS CNVAL, '''' AS INRDR';
END
EXEC (@SQLString);
FETCH NEXT FROM Atr_Cursor
INTO @atr;
END
CLOSE Atr_Cursor;
DEALLOCATE Atr_Cursor;
Obviously, this statement returns several results due to the loop. While trying to use this statement with my C# code, I can only get the result of the last loop (obviously too). So I tried to transer the results into a temporary table; that worked. But now I’ve got the problem that I am not able to build the “complement” of that statement, so that the results are written back into the table.
If it is possible to change the query, so that there are no more loops, I think building the complement of the query will be easier.
So in fact my question is: Is there a chance to change the statement, so that there are no more loops? How could that look like? And if it’s not possible, how will I have to build a complement of that statement?
Thanks a lot for any help.
I think this query will do it.
I used this schema. Please let me know which columns are wrong.